%%% File: mfpic.tex
%%% A part of mfpic 0.6b 2003/01/02
%%%
%%  Now: supports Metapost, including color.
%%  Major changes contributed by Jaromir Kuben, Mar 2000
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Picky startup stuff:
{\catcode`.12 \catcode`/12%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Keep track of version numbers here.
% Revert to latex-style format
\gdef\mfpfileversion{0.6b beta}%
\gdef\mfpfiledate{2003/01/02}%
}%
%
% Started numbering with 0.3.0 when MP support was started.
% Added to the last decimal with substantial changes.
% Change date with any changes.
% Now: starting with 0.5g (was 0.5.07) increment letter any
%      substantial change, increment number for major releases.
%      Change date on any change.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check whether mfpic already loaded:
\ifx\MFPicpackagE\UndEfInEd\else\expandafter\endinput\fi%
%%%%%%%%%%%%%%%%%
% \begin{paranoia}
% Get rid of unusually catcoded punctuation, space and EOL.
% Try to assume only:
% that letters are letter, numbers are other, and
%   "\", "{", "}", "#" and "%" have the usual \catcodes.
% (Styles that make punctuation (e.g., french) active foul up \write's
%  of MF/MP code. This can still occur in user-generated \write's,
%  so maybe some code should be added in \mfpic or \mfsrc command too.)
% Start with lq, EOL, space and equal:
\edef\MFPrestorelq{%
\catcode\lq\lq\the\catcode\lq\`\relax}%
\catcode\lq\`12%
\edef\MFPrestoreEOL{%
\catcode`\^^M\the\catcode`\^^M\relax}%
\catcode`\^^M5
\edef\MFPrestorespace{%
\catcode`\space\the\catcode`\ \relax}%
\catcode`\ 10
\edef\MFPrestoreequal{%
  \catcode`\string =\the\catcode`\=\relax}%
\catcode`\=12
%
% The following will be invoked at the end of this file
% to restore all the catcodes:
\def\MFPrestorecode#1{\catcode`\string#1=\the\catcode`#1\relax}%
\edef\MFPicpackagE{%
  \MFPrestorecode{-}%
  \MFPrestorecode{@}%
  \MFPrestorecode{:}%
  \MFPrestorecode{;}%
  \MFPrestorecode{.}%
%
  \MFPrestorecode{,}%
  \MFPrestorecode{!}%
  \MFPrestorecode{?}%
  \MFPrestorecode{(}%
  \MFPrestorecode{)}%
%
  \MFPrestorecode{'}%
  \MFPrestorecode{/}%
  \MFPrestorecode{"}%
  \MFPrestorecode{*}%
  \MFPrestorecode{$}%
%
  \MFPrestorecode{_}%
  \MFPrestorecode{>}%
  \MFPrestorecode{<}%
  \MFPrestorelq
  \MFPrestoreEOL
%
  \MFPrestorespace
  \MFPrestoreequal
}%
% Set everything to normal except @=letter and $=other
\catcode`\@=11
\def\mfp@sanitize{%
\catcode`\@=11
\catcode`\-=12
\catcode`\:=12
\catcode`\;=12
\catcode`\.=12
%
\catcode`\,=12
\catcode`\!=12
\catcode`\?=12
\catcode`\(=12
\catcode`\)=12
%
\catcode`\'=12
\catcode`\/=12
\catcode`\"=12
\catcode`\*=12
\catcode`\$=12
%
\catcode`\_=12
\catcode`\`=12
\catcode`\^^M=5
\catcode`\ =10
\catcode`\==12
%
\catcode`\>=12
\catcode`\<=12
}%
\mfp@sanitize
%\end{paranoia}
% To turn on debugging before option processing, make sure
% \mfpicdebug is not \undefined:
\newif\ifmfpicdebug  % no @'s because this is a "user-level" command
\ifx\mfpicdebug\UndEfInEd
  \mfpicdebugfalse
\else
  \mfpicdebugtrue
\fi
\def\MFPdebugwrite#1{\ifmfpicdebug\wlog{MFpic: #1 }\fi}%
\def\mfp@msg{\immediate\write16\space}%
\def\MFpic@msg#1{\mfp@msg{MFpic: #1 }}% Just adds text "MFpic:"
\def\MFpic@warn#1{\mfp@msg{MFpic warning: #1 }}% adds "warning"
%
\let\@xp\expandafter
\def\@XP{\expandafter\expandafter\expandafter}%
\ifx\inputlineno\UndEfInEd\def\on@line{}\def\@mfplineno{}\else
\def\on@line{ on line \number\inputlineno}%
\def\@mfplineno{line \number\inputlineno\space in TeX source}%
\fi
%%%%%%%%%%%%%%%%%%%%
% Error messages
%
\def\mfp@errmsg#1#2{%
  {\newlinechar=`\^^J%
   \errhelp{#2}%
   \errmessage{MFpic error: #1 }}%
}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% For testing I change \grafbasename to "graftest":
\def\grafbasename{grafbase}%
%%%
% Testing macro:
\def\mfp@ifdefined#1{%
  \ifx#1\UndEfInEd
    \@xp\@secondoftwo
  \else\ifx#1\relax
    \@XP\@secondoftwo
  \else
    \@XP\@firstoftwo
  \fi\fi
}%
\long\def\@firstoftwo#1#2{#1}%
\long\def\@secondoftwo#1#2{#2}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Tests for format (I ought to see
% whether ConTeXt can be included)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Testing for (any release of) LaTeX.
\newif\ifin@latex
\newif\ifin@amstex
\mfp@ifdefined\documentstyle
 {\def\amstexfmtname{AmS-TeX}%
  \ifx \fmtname\amstexfmtname
    \in@amstextrue
    \MFPdebugwrite{AmS-TeX detected.}%
  \else % not AmS-TeX so assume LaTeX.
    \in@latextrue
    \MFPdebugwrite{LaTeX detected.}%
  \fi}%
 {\MFPdebugwrite{Neither LaTeX2e nor LaTeX209 nor AmS-TeX.}}%
%%%
\ifin@latex
\else
  \let\@@par\endgraf
\fi
\def\mfp@restorepar{\let\par\@@par}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Test specifically for LaTeX2e:
\newif\ifin@LaTeXe
\mfp@ifdefined\documentclass
 {\in@LaTeXetrue
  \MFPdebugwrite{LaTeX2e detected.}}%
 {\MFPdebugwrite{Not LaTeX2e.}}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Test if pdftex support is needed:
\newif\ifin@pdftex
\mfp@ifdefined\pdfoutput
 {\MFPdebugwrite{PdfTeX detected...}%
  \ifcase\pdfoutput
    \MFPdebugwrite{with dvi output.}%
  \else
    \in@pdftextrue
    \MFPdebugwrite{with PDF output.}%
  \fi}%
 {\MFPdebugwrite{Not pdfTeX.}}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% New macros for defining things
\MFPdebugwrite{Defining test for previous definitions of macros.}%
% (Cannot use \testdef to pre-test \testdef, without circular definition.)
\mfp@ifdefined\testdef
  {\MFpic@warn{Hey!  How can testdef already be defined?
     I'll define it, anyway!}}%
  {}%
%
% Define the test for whether a macro name is already defined.
\def\testdef#1{%
  \ifx#1\UndEfInEd
  \else\ifx#1\relax
    \MFpic@warn{\string #1 was previouly defined to be \string\relax!}%
  \else
    \MFpic@warn{Beware! \string #1 is already defined!}%
  \fi\fi}%
% Warn if macro defined, but `let' it anyway.
\testdef\newlet
\def\newlet#1{\testdef#1\let#1}%
% Is the proposed definer of new definitions itself not new?
\testdef\newdef
% Warn if macro previously defined, but still redefine it.
\def\newdef#1{\testdef#1\def#1}%
\def\newgdef#1{\testdef#1\gdef#1}%
% Redefine macro.
\newlet\redef=\def
%%% Here ends \testdef, etc.
%%%%%%%%%%%%%%%%%%%%%%
%% Setting up options
%%
% Certainly the choice of Metafont or MetaPost needs to be global,
% and mutually exclusive:
\newif\if@mfp@metapost
\newdef\mfp@metaposttrue{%
  \global\@mfp@metaposttrue
}%
\newdef\mfp@metapostfalse{%
  \global\@mfp@metapostfalse
}%
% Selecting Metapost or Metafont:
\newdef\usemetafont{\mfp@metapostfalse}%
\usemetafont% default
% (Postpone definition of \usemetapost to LaTeX options section)
% but define error message here:
\def\MPtoolate@error{%
  \mfp@errmsg
   {Command \string\usemetapost\space too late.}%
   {It is too late to select the metapost option.^^J%
    It must be selected before the \opengraphsfile command.}%
}%
%%%
% Centering caption lines:
\newif\if@mfp@centercaptions
\newdef\usecenteredcaptions{\@mfp@centercaptionstrue}%
\newdef\nocenteredcaptions{\@mfp@centercaptionsfalse}%
%%%
% Some options need an open .mf file before they can do anything:
\newdef\@if@mfp@beforefileopen{%
  \ifx\mfp@filename\UndEfInEd\@xp\@firstoftwo\else\@xp\@secondoftwo\fi}%
%%%
% A "clip" option (show only what's inside the rectangle
% given in \mfpic...):
\newif\if@mfp@clip
\@mfp@clipfalse
% Need to be carefule with globality of clip to keep
% TeX and MF in sync
\def\mfp@clip#1{
  \@if@mfp@beforefileopen
    {\global\csname @mfp@clip#1\endcsname}%
    {\csname @mfp@clip#1\endcsname\set@mfvariable{boolean}{clipall}{#1}}%
}%
\def\clipmfpic{\mfp@clip{true}}%
\def\noclipmfpic{\mfp@clip{false}}%
%%%
% Option to let MP set the true bbox (which may differ from
% the numbers defined through \mfpic...). This has to be global:
\newif\if@mfp@truebbox
% Need to be carefule with globality of truebbox to keep
% TeX and MF in sync
\def\mfp@truebbox#1{%
  \@if@mfp@beforefileopen
    {\global\csname @mfp@truebbox#1\endcsname}%
    {\global\csname @mfp@truebbox#1\endcsname
     \mfsrc{truebbox:=#1;}}%
}%
\newdef\usetruebbox{\mfp@truebbox{true}}%
\newdef\notruebbox{\mfp@truebbox{false}}%
\notruebbox
%%%
% Some options require the metapost option:
\def\noMP@error#1{%
  \mfp@errmsg
   {Metafont does not support #1, use Metapost.}%
   {Metafont doesn't support #1. Perhaps you forgot to turn on^^J%
    MetaPost support by using the metapost option or issuing the^^J%
    command \usemetapost. For now, I'm ignoring it.}%
}%
%%%
% Option to let MP create labels
\newif\if@mfp@mplabels
\newdef\usemplabels{%
  \@if@mfp@beforefileopen
    {\global\@mfp@mplabelstrue}%
    {\if@mfp@metapost
      \@mfp@mplabelstrue
     \else
      \@mfp@mplabelsfalse
      \noMP@error{mplabels}%
     \fi}%
}%
\newdef\nomplabels{%
  \@if@mfp@beforefileopen
    {\global\@mfp@mplabelsfalse}%
    {\@mfp@mplabelsfalse}%
}%
%%%
% \setmfpicgraphic is the command that will place each figure.
% In (pdf)LaTeX it is just \includegraphics
% \@setmfpicgraphic is a wrapper around it.
\def\@setmfpicgraphic{\setmfpicgraphic}% default is no wrapping
% \setfilename can be changed to modify the filenames:
\newdef\setfilename#1#2{#1.#2}%
% Adjustments when truebbox is in effect, default is none.
\newdef\mfpicllx{0}%
\newdef\mfpiclly{0}%
%
\newif\if@mfp@draft
\def\mfpicdraft{\global\mfpicdrafttrue\global\@mfp@drafttrue}%
\newif\if@mfp@final
\def\mfpicfinal{\global\mfpicdraftfalse\global\@mfp@finaltrue}%
\newif\if@mfp@nowrite
\def\mfpicnowrite{\global\@mfp@nowritetrue}%
\ifin@LaTeXe
  \ProvidesPackage{mfpic}[2003/01/02 v0.6b beta.]%
  %%%%%%%%%%
  % options
  \DeclareOption{draft}{\global\@mfp@drafttrue}%
  \DeclareOption{final}{\global\@mfp@finaltrue}%
  \DeclareOption{nowrite}{\global\@mfp@nowritetrue}%
  \DeclareOption{metapost}{\mfp@metaposttrue}%
  \DeclareOption{metafont}{\usemetafont}%
  \DeclareOption{centeredcaptions}{\usecenteredcaptions}%
  \DeclareOption{clip}{\clipmfpic}%
  \DeclareOption{truebbox}{\usetruebbox}%
  \DeclareOption{mplabels}{\usemplabels}%
  \DeclareOption{debug}{\mfpicdebugtrue}%
  \DeclareOption*{%
    \@ifpackageloaded{graphics}{%
      \MFpic@warn{Unrecognized option \CurrentOption.}%
    }%
      {\MFpic@msg{Passing option \CurrentOption to graphics package.}%
       \PassOptionsToPackage{\CurrentOption}{graphics}}%
  }%
  % Use star form  of \ProcessOptions so mfpic's "final" option can
  % counteract the side effects of a global "draft" option:
  \ProcessOptions*\relax
  \def\usemetapost{%
    \ifx\mfp@filename\UndEfInEd%
      \mfp@metaposttrue  % global
      \RequirePackage{graphics}%
      \global\let\mfpsaveGread@parse@bb\Gread@parse@bb
      \gdef\mfpic@parse@bb##1 ##2 ##3 ##4 ##5\\{%
        \mfpsaveGread@parse@bb##1 ##2 ##3 ##4 ##5\\%
          \xdef\mfpicllx{\Gin@llx}%
          \xdef\mfpiclly{\Gin@lly}%
      }%
      \ifin@pdftex
        \def\mfp@Gtype{mps}%
      \else
        \def\mfp@Gtype{eps}%
      \fi
      \gdef\getmfpicoffset{}%
      \gdef\@setmfpicgraphic##1{%
        \let\Gread@parse@bb\mfpic@parse@bb
        \setmfpicgraphic{##1}\getmfpicoffset}%
    \else
      \mfp@metapostfalse\MPtoolate@error
    \fi
    \gdef\setmfpicgraphic{\includegraphics}%
  }%
  % \ProcessOptions doesn't allow \RequirePackage{graphics}.
  % That's why the following was not simply put inside
  % \DeclareOption{metapost}. And that's reasonable, since
  % some options might be passed to graphics
  \if@mfp@metapost
    \usemetapost
  \fi
\else
  \MFpic@msg{\mfpfiledate\space v\mfpfileversion.}%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % Commands for selecting options
  % The following is long to cater to several methods of
  % graphic inclusion
  \def\usemetapost{%
    \ifx\mfp@filename\UndEfInEd%
      \mfp@metaposttrue
      %%%%%%%%
      %pdfTeX:
      \ifin@pdftex
        % Give \+ a safe(?) non-expandable, non-\outer meaning while
        % reading supp-mis:
        \@xp\let\@xp\save@plus\csname \string+\endcsname
        \@xp\def\csname \string+\endcsname{+}%
        \mfp@ifdefined\convertMPtoPDF
          {}{\input supp-pdf\relax}%
        % Restore saved meaning of \+.
        \@xp\let\csname\string+\@xp\endcsname\csname save@plus\endcsname
        \gdef\setmfpicgraphic##1{\convertMPtoPDF{##1}{1}{1}}%
        \gdef\getmfpicoffset{%
          \xdef\mfpicllx{\MPllx}%
          \xdef\mfpiclly{\MPlly}%
        }%
      \else
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %plainTeX, AMS-TeX, LaTeX2.09
        \mfp@ifdefined\epsfbox
          {}{\input epsf}%
        \gdef\setmfpicgraphic{\epsfbox}%
        \gdef\getmfpicoffset{%
          \xdef\mfpicllx{\epsfllx}%
          \xdef\mfpiclly{\epsflly}%
        }%
      \fi
      \gdef\@setmfpicgraphic##1{\setmfpicgraphic{##1}\getmfpicoffset}%
    \else
      \mfp@metapostfalse\MPtoolate@error
    \fi
  }%
\fi
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Handle Optional Parameters in TeX macros:
%%%
\MFPdebugwrite{Handlers for optional parameters.}%
% We copy LaTeX's \@ifnextchar, to have the advantage of
% skipping spaces, but skip \relax also.
\long\def\mfp@ifnextchar#1#2#3{%
  \let\mfptmp@d=#1%
  \def\mfptmp@a{#2}%
  \def\mfptmp@b{#3}%
  \mfp@checknext
}%
\def\mfp@checknext{\futurelet\@let@token\mfp@ifnch}%
\def\mfp@ifnch{%
  \ifx\@let@token\@sptoken
    \let\mfptmp@c\eatspace@checknext
  \else\ifx\@let@token\relax
    \def\mfptmp@c##1{\mfp@checknext}%
  \else\ifx\@let@token\mfptmp@d
    \let\mfptmp@c\mfptmp@a
  \else
    \let\mfptmp@c\mfptmp@b
  \fi\fi\fi
  \mfptmp@c
}%
\begingroup
  \def\:{\global\let\@sptoken= }\: % makes \@sptoken a space token
  \def\:{\eatspace@checknext}\@xp\gdef\: {\mfp@checknext}%
\endgroup
%%%   \do@ptparam:
%%%   #1 is command to use (without "\"), #2 is default value of
%%%   optional argument. #1 must be defined, and it must be a command
%%%   whose first argument is delimited by [ and ].
\newdef\do@ptparam#1#2{%
  \mfp@ifnextchar[{\csname#1\endcsname}{\csname#1\endcsname[#2]}%
}%
%%% \alt@ptparam: #1 is code to use if [] are present, #2 if not.
%%% #1 must end with code that handles the optional parameter.
\newdef\alt@ptparam{\mfp@ifnextchar[}%
% Star forms:
\newif\if@mfp@star@
% Little utility to process empty optional parameters
%   (some optional parameters produce inscrutable errors if
%    empty arguments are used. We try to proceed gracefully.)
% #1 is parameter to test (passed by some other macro)
% #2 is what to use if not empty (normally = #1)
% #3 is default to substitute if empty.
% #4 is command being passed the optional argument
\newdef\do@mtparam#1#2#3#4{%
  \if$#1$\def\mfp@param@{[#3]}\else\def\mfp@param@{[#2]}\fi
  \@xp#4\mfp@param@}%
%%% End of Optional Parameters code.
%%%
%
%%%%%%%%%%%%%%%
% Output macros (writing to .mf/p file)
\MFPdebugwrite{Direct output to Metafont/Post file.}%
%
%%%%%%%%%%%%%%%%%%%%%%%
% Preserving linebreaks
% We must
% 1. Require active ^^M to be \let equal to something unexpandable
%   (so \write won't expand it).
% 2. That "something" should have no effect for eol's outside \write s
%
% \let^^M=\relax seems to fulfill both requirements, and is not
% likely to ever be redefined. It is actually a slightly better choice
% than \endgraf (which works) because \relax is permitted before the
% opening brace in the syntax of <general text> (for token variable
% assignments, \write, \message, and the like).
{\catcode`\^^M\active%
  \newgdef\mfpicobeylines{\catcode`\^^M\active\let^^M\relax}%
  \global\let^^M\relax}%
%
% \preservelines is intended to be used to retain line separations
% __when writing the Metafont file__.
%
\newdef\preservelines{%
%%%
% The character assigned to \newlinechar will produce a newline
% when it occurs in a \write.
  \mfpicobeylines%
  \newlinechar=`\^^M}%
%
% Restore carriage return input character and new line behavior
% to usual conduct in formats consistent with plain TeX.
\newdef\unpreservelines{\catcode`\^^M=5 }%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Write argument to MF file.
%
% The \endgroup is an attempt to localise the change to the newline
% character, which was reported by Dan Luecking 1996 Dec 9 Mon.
% the \newlinechar
\newdef\@mfsrc#1{%
   \immediate\write\mfp@out{#1}%
  \endgroup
  \ignorespaces
}%
%
% DHL: The \preservelines in \mfsrc doesn't often do any good: arguments
% are usually read by figure macros and then read again by \@figmac and
% only THEN passed on to \mfsrc! Also, \preservelines is the default
% status inside \mfpic..\endmfpic.  Outside, it may be useful.
%
% The \begingroup matches the \endgroup in \@mfsrc.
\newdef\mfsrc{%
  \@if@mfp@beforefileopen
    {\nooutputfileerror{\mfsrc}}%
    {\begingroup\preservelines\@mfsrc}%
}%
%
% Useful abbreviation.
% Usage: \set@mfvariable{type}{name}{value}
%
\def\set@mfvariable#1#2#3{\mfsrc{save #2; #1 #2; #2:=#3;}}%
%
%%%%%%%%%%%%%%%%%%%%
% Special characters
%
% Percent, Sharp and Backslash signs for Metafont file:
% \edef's make sure the first level expansion is just one character
% token with category 12:
\newdef\mfp@gobble#1{}%
\edef\mf@p{\@xp\mfp@gobble\string\%}%   percent (%)
\edef\mf@s{\@xp\mfp@gobble\string\#}%   sharp (#)
\edef\mf@b{\@xp\mfp@gobble\string\\}%   backslash (\)
%
% Used to mark ends of things, \mfp@delim should never expand;
% but we give it a definition for debugging purposes:
\newdef\mfp@delim{%
  \mfp@errmsg
   {Misplaced \string\mfp@delim.}%
   {If you get this message but did not (mis)use the command^^J
    \mfp@delim, please report this to the mfpic maintainer.}}%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%
% Date,time stamp for .mf file:
%% \normalyear and \normalmonth are ConTeXt
{%
  \mfp@ifdefined\normalmonth
  {\let\month\normalmonth\let\year\normalyear}{}%
  \xdef\mfp@today{\number\day/\number\month/\number\year}%
}%
% Calculating timestamp in hh:mm format:
% (using \count2 as scratch register)
{\count2=\time
\divide\count2 by 60
\xdef\mfp@now{\ifnum\count2<10 0\fi\number\count2:}%
% note \mfp@now now contains hh:
\multiply\count2 by -60
\advance\count2 \time % \count2 is now number of min. past the hour
\xdef\mfp@now{\mfp@now\ifnum\count2<10 0\fi\number\count2 }%
}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initializing the output file
\MFPdebugwrite{Declarations used with data and graphs files.}%
\newwrite\mfp@out      % The .mf file
\newread\mfp@graph     % used to test existence of graphics file
\newcount\mfp@count    % keeps track of current graphic number
\newcount\mfp@linetype % keeps track of line styles in ploting data files
\newtoks\mfp@toks      % temporary token reg for \write s
\newtoks\every@tlabel  % inserted at every tlabel
\every@tlabel{}%
\newtoks\mfp@commonverbatimtex
\begingroup
  \let\newtoks\relax
  \catcode`\#=12
  \catcode`\%=12
  \preservelines
  \global\mfp@commonverbatimtex=
    {\newtoks\everytlabel
     \def\MFPtext#1{%
        \vbox{\def\\{\cr}\MFPcfont\the\everytlabel
        \halign{##\hfil\cr#1\crcr}}}%
    }\endgroup
%%%
%%% Open and Close Metafont/Post Graphs file:
%%%
\MFPdebugwrite{Macros to open and close graphs files.}%
%
% To help avoid errors from graphic inclusion macros:
\newif\ifmfpicdraft
%
\newdef\opengraphsfile#1%
{% save filename for later use:
  \gdef\mfp@filename{#1}%
  \if@mfp@metapost
    \if@mfp@nowrite\else
      \immediate\openout\mfp@out=#1.mp\relax
    \fi
    % Does at least one figure exist:
    \openin\mfp@graph=\setfilename{#1}{\number\mfp@count}\relax
    \ifeof\mfp@graph                            % no figs
      \MFpic@msg{No file \setfilename{#1}{\number\mfp@count}.}%
      \gdef\setmfpicgraphic##1{}%
      \global\let\@setmfpicgraphic\setmfpicgraphic % remove any wrapping
      \global\mfpicdrafttrue
    \else                                       % at least first fig
      \global\mfpicdraftfalse
    \fi
    \closein\mfp@graph
    \MFpic@msg{Don't forget to process #1.mp!}%
    \MFpic@msg{(Apply metapost to #1.mp.)}%
  \else                                      % metafont option
    \if@mfp@nowrite\else
      \immediate\openout\mfp@out=#1.mf\relax % output file
    \fi
    \openin\mfp@graph=#1.tfm\relax         % TFM exists?
    \ifeof\mfp@graph                       % no
      % MF graphics don't exist:
      \MFpic@msg{No file #1.tfm .}%
      \gdef\setmfpicgraphic##1{}%
      \global\font\@graphfont=dummy\relax
      \global\mfpicdrafttrue
    \else                                  % yes
      % Don't know if \global is necessary here:
      \global\font\@graphfont=#1\relax            % load the font
      \gdef\setmfpicgraphic##1{\@graphfont\char\mfp@count}%
      \global\mfpicdraftfalse
    \fi
    \closein\mfp@graph                     % end of TFM existence test
    \MFpic@msg{Don't forget to process #1.mf!}%
    \MFpic@msg{(Apply metafont to #1.mf, %
        then gftopk to the resulting gf file.)}%
  \fi                                      % end of metafont option
  \if@mfp@draft\global\mfpicdrafttrue\fi
  \if@mfp@final\global\mfpicdraftfalse\fi
  \MFpic@msg{Then reprocess this file (\jobname).}%
  \mfp@msg{}%
  \if@mfp@nowrite\let\mfsrc\mfp@gobble\fi
  %%% Common preamble of .mf/p file:
  \mfsrc{\mf@p\space \mfp@filename.\if@mfp@metapost mp\else mf\fi,
          generated by MFpic, %
          v\mfpfileversion\space\mfpfiledate,}%
  \mfsrc{\mf@p\space from TeX source \jobname\space on \mfp@today\space at \mfp@now}%
  \mfsrc{if unknown mode: mode:= localfont; fi}%
  \mfsrc{if unknown mag: mag:=\number\mag/1000; fi}%
  \mfsrc{if unknown grafbase: input \grafbasename; fi}%
  % dvips names for colors:
  \if@mfp@metapost
    \mfsrc{}%
    \mfsrc{input dvipsnam.mp}%
  % Write the verbatimtex stuff if previously declared.
  % Since mplabels might be turned on later:
    \mfsrc{}%
    \mfsrc{verbatimtex}%
    \mfsrc{\the\mfp@commonverbatimtex}
    % If \mfpverbtex is used before \opengraphsfile:
    \if@mfp@verbtex
      \mfsrc{\the\mfp@verbtex}%
    \fi
    \mfsrc{\noexpand\everytlabel{\the\every@tlabel}}%
    \mfsrc{etex}%
  \fi
  \if@mfp@mplabels
    \global\usemplabels
  \fi
  \if@mfp@clip
    \mfsrc{}%
    \global\clipmfpic
  \fi
    \mfsrc{}%
    \mfsrc{boolean truebbox;}%
  \if@mfp@truebbox
    \usetruebbox % always global
  \else
    \notruebbox
  \fi
  \ignorespaces
}%
\newdef\closegraphsfile
{% Guard against \close without \open
  \@if@mfp@beforefileopen
    {\nooutputfileerror{\closegraphsfile}}%
    {\mfsrc{}%
     \mfsrc{end.}%
     \if@mfp@nowrite\else
       \immediate\closeout\mfp@out
     \fi
     \global\let\mfp@filename\UndEfInEd}%
}%
%
% If we have several macros check for the graph file having been open,
% we'll need a generic error message. (So far we use it only twice):
\def\nooutputfileerror#1{%
  \mfp@errmsg
   {No output file has been opened.}%
   {You have tried to used a command, #1, that requires an output^^J%
    file, opened with the \opengraphsfile command. Things are unlikely^^J%
    to turn out well.}%
}%
%
% Resetting the mfpic graph number:
\newdef\mfpicnumber#1{\global\mfp@count=#1\relax}%
%
%%%%%%%%%%%%%%%%%%%%%%%%
% Storing new dimensions
%
% We use font dimensions to spare TeX's dimension registers.
%
\MFPdebugwrite{Using dummy font's dimensions, to spare TeX registers.}%
%
% Load dummy.tfm : most systems should have this,
% but other fonts (such as cmr10) may suffice.
% Load it at an unusual scaling lest some previous
% package already co-opted it:
%
\font\@dummy=dummy scaled 1042
\fontdimen100\@dummy=0pt
% The above should give an extra 78 dimensions for our use.
%
% In the web2c Metafont 2.71 implementation,
% each font initially has 22 dimensions.
% This number can be increased only by using a higher font
% dimension number immediately after the font is loaded.
% (It has to be done before another font is loaded, not
% _immediately_.)
%
% Use an auxiliary count register to keep track of new font dimens:
%
\newcount\@fdc
%
% Most fonts use only font dimensions 1 to 22; start new font
% dimensions from number 23 to avoid mangling the font's typesetting.
% (For dummy.tfm, this may not matter, as it has no characters.)
%
\@fdc=23
%
% Rough equivalent of \newdimen, only for font dimensions.
% Note:  \newfdim defines a dimension globally, like \newdimen.
% Must define carefully, to use the current font dimension number.
% (\@fdc holds the next available \fontdimen number)
\newdef\newfdim#1{\xdef#1{\fontdimen\number\@fdc\@dummy}%
                   \global \advance\@fdc by 1\relax}%
%
% Drawback 1:  Font dimension assignments seem always to have global scope.
% Drawback 2:  Font dimensions cannot directly use \advance, \multiply
% or \divide.  One must copy to and from a temporary TeX dimension
% register.
%
%%%%%%%%%%%%%%%%%%%%%%%
% The boxes we will use:
\MFPdebugwrite{A box register for whole labeled graph, and a temporary one.}%
\newbox\@wholegraph
\newbox\@textbox
\newdef\mfp@tbht{\ht\@textbox}%
\newdef\mfp@tbdp{\dp\@textbox}%
\newdef\mfp@tbwd{\wd\@textbox}%
%%%%%%%%%%%%%%%%%%%%%%%%%
% And the many dimensions:
\MFPdebugwrite{Internal dimension parameters for graph dimensions.}%
% 5 for graph dimensions
\newfdim\@graphwd
\newfdim\@graphright
\newfdim\@graphleft
\newfdim\@graphht
\newfdim\@graphdp
% 2 for label offsets
\newfdim\tlabel@hadj
\newfdim\tlabel@vadj
\tlabel@hadj=0pt
\tlabel@vadj=0pt
% 15 more for graphic objects
\MFPdebugwrite{User level dimension parameters, with default settings.}%
\newfdim\mfpicunit
\newfdim\pointsize
\newfdim\shadespace
\newfdim\polkadotspace
\newfdim\hatchspace
\newfdim\headlen
\newfdim\axisheadlen 
\newfdim\sideheadlen
\newfdim\hashlen
\newfdim\dashlen
\newfdim\dashspace
\newfdim\dotsize
\newfdim\dotspace
\newfdim\symbolspace
\newfdim\tlabel@sep
% Initialize:
\mfpicunit=1pt
\pointsize=2pt
\shadespace=1pt
\polkadotspace=10pt
\hatchspace=3pt
\headlen=3pt
\axisheadlen=5pt
\sideheadlen=0pt
\hashlen=4pt
\dashlen=4pt   % should be less than space, considering pen's width
\dashspace=4pt
\dotsize=0.5pt
\dotspace=3pt
\symbolspace=5pt
\tlabel@sep=0pt
%
% The following is used to save and restore the above on entering and
% exiting an mfpic environment. Localizes changes inside pictures.
% (the \@graph... don't need saving since they are reset with each
% picture.)
\newdef\save@mfpicdimens{%
  \edef\restore@mfpicdimens{%
    \mfpicunit     =\the\mfpicunit
    \pointsize     =\the\pointsize
    \shadespace    =\the\shadespace
    \polkadotspace =\the\polkadotspace
    \hatchspace    =\the\hatchspace
    \headlen       =\the\headlen
    \axisheadlen   =\the\axisheadlen
    \sideheadlen   =\the\sideheadlen
    \hashlen       =\the\hashlen
    \dashlen       =\the\dashlen
    \dashspace     =\the\dashspace
    \dotsize       =\the\dotsize
    \dotspace      =\the\dotspace
    \symbolspace   =\the\symbolspace
    \tlabel@hadj   =\the\tlabel@hadj
    \tlabel@vadj   =\the\tlabel@vadj
    \tlabel@sep    =\the\tlabel@sep
  }%
}%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% (Utilities to manipulate these dimensions no longer used)
%
% A utility to do real arithmetic:
% #1 is a macro that expands to some number
% #2 is a number to add to it. The result is
% stored again in #1 (i.e., the old value is overwritten).
%
\newdimen\mfp@scratch
%
\newdef\mfp@addto#1#2{\mfp@scratch=#1pt\advance\mfp@scratch#2pt%
  \edef#1{\@xp\mfp@rem@pt\the\mfp@scratch}%
}%
\begingroup
  \catcode`P=12
  \catcode`T=12
  \lowercase{%
    \def\x{\def\mfp@rem@pt##1PT{##1}}}%
\@xp\endgroup\x
\def\mfp@identy#1{#1}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% A few user-level utilities:
%
\MFPdebugwrite{Graphics macros.}%
%
%% Point defining macro:
%% #1 = name of point w/o backslash
%% #2,#3 are coordinates
%% Usage \pointdef{A}(2,5) makes
%%  \A expand to (2,5), \Ax to 2, and \Ay to 5.
\newdef\pointdef#1(#2,#3){%
\@xp\def\csname#1\endcsname{(#2,#3)}%
\@xp\def\csname#1x\endcsname{#2}%
\@xp\def\csname#1y\endcsname{#3}%
}%
%
% Standard shade setting macros:
\newdef\darkershade{%
  \shadespace=.833333\shadespace
}%
\newdef\lightershade{%
  \shadespace=1.2\shadespace%
}%
% Note:  \dashlineset is same as initial setting:
\newdef\dashlineset{%
  \dashlen=4pt
  \dashspace=4pt}%
\newdef\dotlineset{%
  \dashlen=1pt
  \dashspace=2pt}%
% User can choose subsequent points to be either filled or open:
\newif\ifpointfill\pointfilltrue
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Setting up prefix commands:
\MFPdebugwrite{Tests to control multiple prefix commands.}%
%
% Start of a complex drawing command (one that includes prefixes).
% Figure macros close by setting it true;
% Rendering and other prefix macros close by setting this false:
\newif\if@startfig\@startfigtrue
%
% Implicit Rendering:
% Rendering macros close by setting this false;
% Figure macros close by setting it true;
% Other prefix macros (eg, \closed and \reverse) do not touch it:
\newif\if@imrend\@imrendtrue
%
% Storage of a path.
\newdef\store@path{\mfsrc{}\mfsrc{store (curpath)}}%
%
% First stage of (rendering and path modification) prefix macros:
\newdef\@firststage{%
  \if@startfig
    \store@path
    \@imrendtrue
    \@startfigfalse
  \fi
}%
%
% Rendering macro specification:
\newdef\@rendmac#1{%
  \@firststage
  \@imrendfalse
  \mfsrc{#1}%
}%
%
% Path modification (eg, path reversal) macro specification:
\newdef\@modmac#1{%
  \@firststage
  \mfsrc{#1}%
}%
%
% Path closure macro specification.
% (Also used for path transformation prefixes)
\newdef\@closmac#1{%
  \@figmacstart
  \mfsrc{#1}%
}%
%
% (Implicitly) Render current figure.
% Initial default is to draw solid paths.
%
\newdef\@render{\draw}%
%
% Redefine (implicit) Render command.
%
\newdef\setrender#1{\redef\@render{#1}}%
%
% Figure macro specification.
%
\newdef\@figmacstart{%
  \@firststage
  \if@imrend
    \@xp\@render
  \fi}%
\newdef\@figmacend{%
  \@startfigtrue
  \@imrendtrue
}%
\newdef\@figmac#1{%
  \@figmacstart
  \mfsrc{#1;}%
  \@figmacend
}%
% Now list arguments can be either a list of pairs
% or a datafile name, either being written to the .mf
% as a list in parentheses.
\newdef\@listmac#1{%
    \@figmacstart\mfsrc{#1}\@figmacdata}%
% These two differ only in that the first has to arrange the
% addition of \@figmacend on the end
\newdef\@figmacdata{%
    \mfp@ifnextchar\datafile{\@figmacdatafile}{\@figmaclist}}%
\newdef\mfp@writedata{%
    \mfp@ifnextchar\datafile{\mfp@writedatafile}{\mfp@writelist}}%
%
% data in argument, write it.
\newdef\@figmaclist{\begingroup\preservelines\@@figmaclist}%
\newdef\@@figmaclist#1{\mfsrc{(#1);}\endgroup\@figmacend}%
\newdef\mfp@writelist{\begingroup\preservelines\mfp@@writelist}%
\newdef\mfp@@writelist#1{\mfsrc{(#1);}\endgroup}%
%
% Data in file. #1 is the token \datafile, #2 is name of file.
\newdef\@figmacdatafile  #1#2{\@processdatafile{#2}{\mfp@rwdata}\@figmacend}%
\newdef\mfp@writedatafile#1#2{\@processdatafile{#2}{\mfp@rwdata}}%
%
% Utility for files
\newdef\mfp@resetwhitespace{%
  \catcode`\^^M=5
  \catcode`\ =10
  \catcode`\^^I=10
}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Titles for the .mf and .tex files.
% (This is only used in our documentation.)
% Metafont title:
\newdef\mftitle#1{{\mfp@title{#1}}}%
% TeX text and Metafont title:
\newdef\tmtitle#1{{%
  \mfp@title{#1}%       Write to mf/p file
  \wlog{\the\mfp@toks}% and to log,
    #1}}%               and in document
\newdef\mfp@title#1{%
  \mfp@toks={#1}%
  \mfsrc{}%
  \mfsrc{mftitle "\the\mfp@toks";}\ignorespaces
}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% To turn off character shipping for duration of
% innermost enclosing group (eg, mfpic environment):
% (As far as I know it has never been tested with MP. DHL)
\newif\if@mfp@shipping
\@mfp@shippingtrue         
\newdef\noship{%
  \mfsrc{save shipit; let shipit = relax;}%
  \@mfp@shippingfalse
}%
%%%%%%%%%%%%%%%%%%%
% Pen size settings:
%
% Macros that write changes in default grafbase variables
% now use the construct "save x; <type> x; x := <value>;"
% This makes changes local if inside a given mfpic
% environment, global if outside. An exception is penwd
% which, as an internal variable uses "interim".
%
% Drawing pen's width:
\newdef\drawpen#1{%
  \mfsrc{}%
  \mfsrc{resizedrawpen(#1);}%
}%
\newlet\pen=\drawpen   % for compatibility
\newlet\penwd=\drawpen % for consistency
%%%
% Shading dot's diameter:
\newdef\shadewd#1{%
  \set@mfvariable{numeric}{shadewd}{\if@mfp@metapost\else ceiling \fi(#1)}%
  \if@mfp@metapost
  \else
    \set@mfvariable{picture}{shadedot}{setdot(dotpath,shadewd)}%
  \fi}%
%%%
% Polka dot's diameter:
\newdef\polkadotwd#1{%
  \set@mfvariable{numeric}{polkadotwd}{\if@mfp@metapost\else ceiling\fi (#1)}%
  \set@mfvariable{picture}{thepolkadot}{setdot(dotpath,polkadotwd)}%
}%
%%%
% Hatch line's thickness:
\newdef\hatchwd#1{%
  \set@mfvariable{numeric}{hatchwd}{#1}%
  \set@mfvariable{pen}{hatchpen}{pencircle scaled hatchwd yscaled aspect_ratio}%
}%
%%%
% Micro-adjustment in \tlabels
% Separation of label from its point:
\newdef\tlabelsep#1{%
  \tlabel@sep=#1\relax
  \set@mfvariable{numeric}{label_sep}{\the\tlabel@sep}%
}%
%%%
%Append tokens before \tlabels
\newdef\everytlabel{\afterassignment\ev@rytlabel\every@tlabel}%
\newdef\ev@rytlabel{%
  \if@mfp@mplabels
    \@if@mfp@beforefileopen{}%
    {\mfsrc{verbatimtex \noexpand\everytlabel{\the\every@tlabel} etex}}%
  \fi
  \ignorespaces
}%
%%%%%%%%%%%%%%%%%%
% Other settings
%%%
% Arrowhead shape setting:
\newdef\headshape#1#2#3{\mfsrc{}\mfsrc{headshape (#1, #2, #3);}}%
%%%
% Basic color variable setting:
% Write a color assignment to the .mp file:
\newdef\mfpwritecolor#1#2{%
  \if@mfp@metapost
    \set@mfvariable{color}{#1}{#2}%
  \else
    \noMP@error{color}%
  \fi}%
% Match LaTeX's \definecolor syntax:
\newdef\mfpdefinecolor#1#2#3{\mfpwritecolor{#1}{#2(#3)}}%
% Set up LaTeX style syntax for \fillcolor and family:
\newdef\@mfpcolor#1{\alt@ptparam{\mfp@color{#1}}{\mfpwritecolor{#1}}}%
\newdef\mfp@color#1[#2]#3{\mfpwritecolor{#1}{#2(#3)}}%
%
\newdef\fillcolor{\@mfpcolor{fillcolor}}%
\newdef\drawcolor{\@mfpcolor{drawcolor}}%
\newdef\headcolor{\@mfpcolor{headcolor}}%
\newdef\hatchcolor{\@mfpcolor{hatchcolor}}%
\newdef\tlabelcolor{\@mfpcolor{tlabelcolor}}%
\newdef\backgroundcolor{\@mfpcolor{background}}%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set up switches for plotting datafiles with multiple curves in
% different line types
%%%
% Draw lines in different dash pstterns:
% (6 available beginning with solid)
\newdef\dashedlines{%
  \mfp@linetype0
  \def\mfp@setstyle{%
    \ifnum\mfp@linetype>5 \mfp@linetype=0\relax\fi
    \gendashed{dashtype\number\mfp@linetype}}%
}%
\dashedlines % the default
%%%
% Draw lines in different colors (MP only):
% (8 available, beginning with black)
\newdef\coloredlines{%
  \if@mfp@metapost
    \mfp@linetype0
    \def\mfp@setstyle{%
    \ifnum\mfp@linetype>7 \mfp@linetype=0\relax\fi
    \draw [colortype\number\mfp@linetype]}%
  \else
    \MFpic@warm{Can't use \string\coloredlines\space in Metafont.
    Using \string\dashedlines\space instead}%
    \dashedlines
  \fi
}%
%%%
% Plot lines in different point symbols:
\newdef\pointedlines{%
  \mfp@linetype0
  \def\mfp@setstyle{%
    \ifnum\mfp@linetype>8 \mfp@linetype=0\relax\fi
    \plot{pointtype\number\mfp@linetype}}%
}%
%%%
% Plot only the data points in different symbols:
\newdef\datapointsonly{%
  \mfp@linetype0
  \def\mfp@setstyle{%
    \ifnum\mfp@linetype>8 \mfp@linetype=0\relax\fi
    \plotnodes{pointtype\number\mfp@linetype}}%
}%
\newdef\mfplinetype#1{\mfp@linetype=#1}%
\newlet\mfplinestyle\mfplinetype % Compatibility
% Line styles cycle through 0--max, where max depends on type of line,
% (4 types listed above) user can change the starting value:
\mfplinetype{0}% default
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Commands for setting position of border axes:
% Default is at edge of the graph space (0 offset):
\newdef\mfp@lshift{0}%
\newdef\mfp@bshift{0}%
\newdef\mfp@rshift{0}%
\newdef\mfp@tshift{0}%
%
% #1 is l, b, r, or t to select the axis
% #2 is numeric, in graph coordinates, representing an inward shift amount.
\newdef\axismargin#1#2{%
  \set@mfvariable{numeric}{#1axis}{#2}%
  \@xp\def\csname mfp@#1shift\endcsname{#2}%
}%
\newdef\setaxismargins#1#2#3#4{%
    \axismargin l{#1}%
    \axismargin b{#2}%
    \axismargin r{#3}%
    \axismargin t{#4}%
}%
\newdef\setallaxismargins#1{\setaxismargins{#1}{#1}{#1}{#1}}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Commands for setting the position of tickmarks on border axes:
% #1 is the axis (x, y, l, b, r, or t)
% #2 can be inside, outside or centered;
%    or ontop, onbottom, onleft or onright.
\def\setaxismarks#1#2{\set@mfvariable{numeric}{#1tick}{#2}}%
\newdef\setbordermarks#1#2#3#4{%
  \setaxismarks l{#1}%
  \setaxismarks b{#2}%
  \setaxismarks r{#3}%
  \setaxismarks t{#4}%
}%
% set all side axes marks the same.
\newdef\setallbordermarks#1{\setbordermarks{#1}{#1}{#1}{#1}}%
\newdef\setxmarks#1{\setaxismarks x{#1}}%
\newdef\setymarks#1{\setaxismarks y{#1}}%
% Without these commands the default is to place ticks inside
% for the border axes and centered for the x- an y-axes.
%%%
% Commands to set type of curve (smooth or polygonal).
\newdef\smoothdata{\do@ptparam{@smoothdata}{1}}%
\newdef\@smoothdata[#1]{\def\mfp@smoothness{s}\mfp@tension{#1}}%
\newdef\unsmoothdata{\def\mfp@smoothness{p}\def\mfp@tension{}}%
\unsmoothdata% default
\newcount\mfp@n
\newcount\mfp@sequence
\newdef\mfpdataperline{5}%
%%%
% Commands to control how we interpret data in a file
% and these should be permitted outside mfpictures
\newdef\using#1#2{\def\massage@data#1\mfp@delim{#2}}%
\newdef\usingpairdefault{\using{##1 ##2 ##3}{(##1,##2)}}%
\newdef\usingnumericdefault{\using{##1 ##2}{##1}}%
\usingpairdefault
% Commands used internally by \datafile and \plotdata:
\newdef\mfp@empty{}%
\def\mfp@par{\par}%
\newdef\mfp@join{,}% was "--" for _joining_ nodes into a path
% User can change comment character for data files:
\newdef\mfpdatacomment#1{%
  \edef\mfp@restorecomment{%
    \catcode\number`\%=14 \catcode\number`#1=\number\catcode`#1\relax}%
  \def\mfp@setcomment{\catcode`\%=12 \catcode`#1=14 }%
}%
\newdef\mfp@setcomment{}%
\newdef\mfp@restorecomment{}%
\newdef\makepercentother{\catcode`\%=12 }%
\newdef\makepercentcomment{\catcode`\%=14 }%
% Error messages for missing or empty data files:
\newdef\nodatafileerror#1{%
  \mfp@errmsg
   {No data file: #1 .}%
   {The data file you tried to draw can't be found.}%
}%
\newdef\emptydatafileerror#1{%
  \mfp@errmsg
   {Empty data file: #1 .}%
   {The file you tried to draw contains only empty lines and comments.}%
}%
%%%
% A hook for adding new definitions, \mfp@additions
% is executed last in \@mfpic@graf@macs.
\newdef\mfp@additions{}%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Define mfpic graphics macros.
%
% The macro \@mfpic@graf@macs, loads most of the drawing macro
% definitions, it will be issued at the start of \mfpic,
% localizing all the definitions to the mfpic environments.
% (Is that really necessary?)
%
\newdef\@mfpic@graf@macs
{%
  %% Define (and draw) paths using data read from a file.
  \let\mfp@data\mfp@graph % Reuse handle
  %%%%%%
  % Open a data file, if possible, and process it. ##1 is file name.
  % ##2 is what to do if it exists and is nonempty
  \newdef\@processdatafile##1##2{%
    \openin\mfp@data=##1\relax
    \ifeof\mfp@data
      \nodatafileerror{##1}%
    \else
      \begingroup
        \mfp@resetwhitespace
        \mfp@setcomment
        \skipBlanksandComments
        \ifeof\mfp@data
          \emptydatafileerror{##1}%
        \else
          ##2%
        \fi
        \global\mfp@n=\mfp@linetype
      \endgroup
      \mfp@linetype=\mfp@n % linetype is local, but not to above group
    \fi
    \closein\mfp@data
  }%
  %%%%%
  % \plotdata plots several curves using data from an external file.
  % ##1 is p or s + (optional) tension
  % ##2 is filename
  \newdef\plotdata{\do@ptparam{@plotdata}{\mfp@smoothness\mfp@tension}}%
  \newdef\@plotdata[##1]##2{%
    \@processdatafile{##2}{\mfp@doplots{##1}}%
  }%
  % (expects \mfp@data handle to be open)
  \newdef\mfp@doplots##1{%
      \mfp@setstyle     % writes appropriate rendering macro
      \advance\mfp@linetype1
      \do@datafile{##1}%
      \@figmacend % \@figmacstart from rendering macro in \mfp@setstyle
      % \do@datafile returns when any blank line or eof is read.
      % \@if@enddata checks for eof or double blank lines
      \@if@enddata{}{\mfp@doplots{##1}}%
  }%
  %
  % (expects \mfp@data handle to be open)
  \newdef\skipBlanksandComments{%
%?    \global
    \read\mfp@data to \mfp@temp
    \ifx\mfp@temp\mfp@empty
      \@xp\skipBlanksandComments
    \else    % reading at eof produces \par so check for eof first
      \ifeof\mfp@data
      \else
        \ifx\mfp@temp\mfp@par
          \@xp\@XP\@xp\skipBlanksandComments
        \fi
      \fi
    \fi
  }%
  % (expects \mfp@data handle to be open)
  \newdef\skipcomments{%
    \read\mfp@data to \mfp@temp
    \ifx\mfp@temp\mfp@empty\@xp\skipcomments\fi}%
  %
  % (expects \mfp@data handle to be open)
  \newdef\@if@enddata{% called with \mfp@temp blank, checks for second blank
    \ifeof\mfp@data\relax % was it eof?
      \@xp\@firstoftwo
    \else          % no, check for second blank line
      \skipcomments
      \ifx\mfp@temp\mfp@par
        \@XP\@firstoftwo
      \else
        \@XP\@secondoftwo
      \fi
    \fi
  }%
  %%%
  % \datafile defines a path connecting the points in a datafile.
  % [##1] is smoothness, ##2 is filename.
  % (expects \mfp@data handle to be open)
  \newdef\datafile{\do@ptparam{@datafile}{\mfp@smoothness\mfp@tension}}%
  \newdef\@datafile[##1]##2{%
    \@figmacstart
    \@processdatafile{##2}{\do@datafile{##1}}%
    \@figmacend % outside group of \@processdatafile
  }%
  % \do@datafile is
  % called from \datafile via \@processdatafile
  % so it's inside a group and \mfp@data file handle is open.
  \newdef\do@datafile##1{%
    \do@mtparam{##1}{##1}{\mfp@smoothness\mfp@tension}\@do@datafile
  }%
  %%%
  % \@do@datafile is mainly a wrapper, processing
  % the optional args and writing the rendering code
  % ##1 is s or p
  % ##2 is tension
  % (both passed by \plotdata or \datafile)
  % It is called from \do@datafile and also from \plotdata
  % (via \@processdatafile, so it is inside a group and \mfp@data
  % file handle is open).
  \newdef\@do@datafile[##1##2]{%
    \mfsrc{%
    \if##1s%           % smooth
      \if$##2$%        % absent, use default tension
        curve (false)%
      \else             % tension=##2
        tcurve (##2, false)%
      \fi
    \else
        polyline (false)%
    \fi}%
    \mfp@rwdata
  }%
  % \mfp@rwdata is called within \@processdatafile, so it is
  % inside a group, \mfp@data file handle is open, and \mfp@temp
  % contains a non-blank line. Also whitespace should have its
  % usual meaning.
  \def\mfp@rwdata{%
      % scratch counter for deciding when to write a line:
      \mfp@n=1
      % sequence counter
      \def\sequence{\number\mfp@sequence}%
      \mfp@sequence=1
      \edef\mfp@temp{\mfp@temp\space}% Add a space so we can always
                                     % assume there is at least one.
      \edef\mfp@buffer{% put open paren and first datum into line buffer
        (\@xp\massage@data\mfp@temp\mfp@delim}%
      \mfp@rwdataloop   % does actual reading/writing
  }%
  % After initial setup, implement the reading and writing.
  % Called with \mfp@buffer already containing first data point
  \newdef\mfp@rwdataloop{%
    \read\mfp@data to \mfp@temp % read next datum
    \ifx\mfp@temp\mfp@par
      % finish off path and exit loop
      \mfsrc{\mfp@buffer);}%
    \else
      \ifx\mfp@temp\mfp@empty  % comment line, ignore
      \else % actual datum
        \edef\mfp@temp{\mfp@temp\space}% Add a space to it
        \advance\mfp@sequence1
        % add the "join" (comma) to buffer:
        \edef\mfp@buffer{\mfp@buffer\mfp@join}%
        \ifnum\mfp@n<\mfpdataperline\relax% # of points in output line
          \advance\mfp@n1
          % Add current data to current buffer
          \edef\mfp@buffer{\mfp@buffer\@xp\massage@data\mfp@temp\mfp@delim}%
        \else
          \mfsrc{\mfp@buffer}% write buffer when long enough
          % Start buffer over with new datum:
          \mfp@n=1
          \edef\mfp@buffer{\@xp\massage@data\mfp@temp\mfp@delim}%
        \fi
      \fi
      \@xp\mfp@rwdataloop % do again
    \fi
  }%
  %
  %% Tiling environment:
  %% ##1 = legal Metafont variable.
  \newdef\tile##1{\mfsrc{}\mfsrc{tile (##1);}}%
  \newdef\endtile{\mfsrc{endtile;}\mfsrc{}}%
  %% Path arrays:
  %% Store enclosed paths in Metafont path array.
  %% ##1 = legal Metafont variable name
  \newdef\patharr##1{%
    \begingroup
      \mfsrc{hide(numeric ##1; path ##1[]; ##1 = 0;)}%
      \redef\store@path{\mfsrc{store(##1[incr ##1])}}%
      \setrender{}%
  }%
  \newdef\endpatharr{%
    \endgroup}%
  %%%%%%%%%%%%%%%%%%%%%%
  % The prefix commands:
  %
  %% Storing an mfpic path in a Metafont path variable:
  %% ##1 = legal Metafont variable name
  %% ##2 = mfpic path (e.g. \rect{...})
  \newdef\store##1##2{\mfsrc{}\mfsrc{store(##1)}%
    \@startfigfalse
    \@imrendfalse
      ##2%
    \@imrendtrue
    \@startfigtrue}%
  %% Invoking a stored object.
  %% Allow it to be shaded, connected, etc:
  %% (##1 would normally be a path p stored with \store{p}...,
  %%  but could be something created through \mfsrc.)
  %% ##1 = legal Metafont variable name
  %% ##1 is simply picked up by \@figmac
  \newdef\mfobj{\@figmac}%
  %% Tesselation (tiling):
  %% ##1 = legal Metafont variable name
  \newdef\tess##1{\@rendmac{tess(##1)}}%
  %% Shading:
  %% ##1 = dimension, defaults to \the\shadespace
  \newdef\@shade[##1]{%
    \@rendmac{shade(##1)}%
  }%
  \newdef\shade{\do@ptparam{@shade}{\the\shadespace}}%
  %% polkadot filling:
  %% [##1] = [dimension], defaults to [\the\polkadotspace]
  \newdef\@polkadot[##1]{%
    \@rendmac{polkadot(##1)}%
  }%
  \newdef\polkadot{\do@ptparam{@polkadot}{\the\polkadotspace}}%
  %% Hatching:
  %% [##1] = [dimension, angle], default to [\the\hatchspace,0]
  \newdef\@thatch[##1]{%
    \alt@ptparam{\@@thatch{##1}}{\@@thatch{##1}[hatchcolor]}}%
  %% [##2] = [color], defaults to hatchcolor
  \newdef\@@thatch##1[##2]{%
    \@rendmac{\if@mfp@metapost
        colorthatch(##2)\else
        thatch\fi (##1)}%
  }%
  \newdef\thatch{\do@ptparam{@thatch}{\the\hatchspace, 0}}%
  % Extra hatch macros, for convenience:
  %% upper left to lower right:
  \newdef\@lhatch[##1]{\@thatch[##1,-45]}%
  \newdef\lhatch{\do@ptparam{@lhatch}{\the\hatchspace}}%
  %% upper right to lower left:
  \newdef\@rhatch[##1]{\@thatch[##1,45]}%
  \newdef\rhatch{\do@ptparam{@rhatch}{\the\hatchspace}}%
  %% Cross hatching, \lhatch on top of \rhatch
  \newdef\@@xhatch##1[##2]{%
    \@rendmac{%
      \if@mfp@metapost
        colorthatch(##2)(##1, 45)
        colorthatch(##2)(##1,-45)
      \else
        thatch(##1, 45) thatch(##1,-45)
      \fi}%
  }%
  \newdef\@xhatch[##1]{%
    \alt@ptparam{\@@xhatch{##1}}{\@@xhatch{##1}[hatchcolor]}%
  }%
  \newdef\xhatch{\do@ptparam{@xhatch}{\the\hatchspace}}%
  \newlet\hatch=\xhatch
  %% Filling, Erasing, and Clipping:
  %% [##1] = [color], defaults to fillcolor
  \newdef\gfill{\do@ptparam{@gfill}{fillcolor}}%
  \newdef\@gfill[##1]{%
    \@rendmac{\if@mfp@metapost colorfilled(##1)\else filled\fi}%
  }%
  \newdef\gclear{\@rendmac{unfilled}}%
  \newdef\gclip{\@rendmac{CLIP}}
  %% Arrowhead:
  % \@arrowoption is called for each optional argument encountered
  % ##1 = b, c, l, or r,
  % ##2 =     if ##1=b  dimension, defaults to 0pt
  %       elseif ##1=c  color, defaults to headcolor
  %       elseif ##1=l  dimension, defaults to \the\headlen
  %       elseif ##1=r  number, defaults to 0 deg
  \newdef\@arrowoption[##1]{%
    \if$##1$\else\@@arrowoption[##1]\fi
  }%
  \newdef\@@arrowoption[##1##2]{%
    \if l##1\relax
      \if$##2$\else\gdef\@hlength{##2}\fi
    \else\if r##1\relax
      \if$##2$\else\gdef\@hrotate{##2}\fi
    \else\if b##1\relax
      \if$##2$\else\gdef\@hbackset{##2}\fi
    \else\if c##1\relax
      \if$##2$\else\gdef\@hcolor{##2}\fi
    \fi\fi\fi\fi
  }%
  \newdef\@arrowfour[##1]%
  {%
    \@arrowoption[##1]%
    \@modmac{\if@mfp@metapost colorheadpath(\@hcolor)\else headpath\fi
        (\@hlength, \@hrotate, \@hbackset)}%
  }%
  \newdef\@arrowthree[##1]{%
    \@arrowoption[##1]%
    \do@ptparam{@arrowfour}{}%
  }%
  \newdef\@arrowtwo[##1]{%
    \@arrowoption[##1]%
    \do@ptparam{@arrowthree}{}%
  }%
  \newdef\@arrowone[##1]{%
    \@arrowoption[##1]%
    \do@ptparam{@arrowtwo}{}%
  }%
  % (\def, so eplain won't cause a warning)
  \def\arrow{%
    \gdef\@hlength{\the\headlen}%
    \gdef\@hrotate{0}%
    \gdef\@hbackset{0}%
    \gdef\@hcolor{headcolor}%
    \do@ptparam{@arrowone}{}%
  }%
  %% Solid path:
  %% [##1] = color, defaults to drawcolor
  \newdef\draw{\do@ptparam{@draw}{drawcolor}}%
  \newdef\@draw[##1]{%
    \@rendmac{\if@mfp@metapost colordrawn(##1)\else drawn\fi}%
  }%
  %% Dashed path:
  %% [##1,##2] = [dimension,dimension], defaults to [\the\dashlen,\the\dashspace]
  \newdef\@dashed[##1,##2]{\@rendmac{DASHED(##1,##2)}}%
  \newdef\dashed{%
    \do@ptparam{@dashed}{\the\dashlen,\the\dashspace}%
  }%
  %% ##1 = name of a dashing pattern (dashtype0 through dashtype5
  %%       are predefined
  \newdef\gendashed##1{%
    \@rendmac{gendashed (##1)}%
  }%
  \newdef\dashpattern##1##2{\mfsrc{dashpat(##1)(##2);}}%
  %% Dotted path:
  %% [##1,##2] = [dimension,dimension], defaults to [\the\dotsize,\the\dotspace]
  \newdef\@dotted[##1,##2]{%
    \@rendmac{dotted(##1,##2)}}%
  \newdef\dotted{\do@ptparam{@dotted}{\the\dotsize,\the\dotspace}}%
  %% "dotted" with other shapes
  %% ##1 = dimension, defaults to \the\pointsize
  %% ##2 = dimension, defaults to \the\symbolspace
  %% ##3 = {[Solid]{Triangle,Square,Circle},Plus,Cross,Star}
  \newdef\@plot[##1,##2]##3{%
    \@rendmac{doplot(##3,##1,##2)}%
  }%
  \newdef\plot{\do@ptparam{@plot}{\the\pointsize,\the\symbolspace}}%
  %% Close paths:
  % use a straight line
  \newdef\lclosed{\@closmac{lclosed}}%
  % use a bezier
  \newdef\bclosed{\@closmac{bclosed}}%
  % close smoothly (just ..cycle), can change original path.
  \newdef\sclosed{\@closmac{sclosed}}%
  % use a cubic bezier
  \newdef\cbclosed{\@closmac{cbclosed}}%
  % close smoothly with original path unchanged.
  \newdef\uclosed{\@closmac{uclosed}}%
  %
  %% Reversing a path:
  \newdef\reverse{\@modmac{reverse}}%
  %
  %% Rotating a path:
  %% {##1} = {point, angle}
  \newdef\rotatepath##1{\@closmac{rotatedpath(##1)}}%
  %% shifting a path
  %% ##1 = vector
  \newdef\shiftpath##1{\@closmac{shiftedpath(##1)}}%
  %% scaling a path
  %% {##1} = {point, scale}
  \newdef\scalepath##1{\@closmac{scaledpath(##1)}}%
  %% xscaling a path
  %% {##1} = {xcoord, scale}
  \newdef\xscalepath##1{\@closmac{xscaledpath(##1)}}%
  %% yscaling a path
  %% {##1} = {ycoord, scale}
  \newdef\yscalepath##1{\@closmac{yscaledpath(##1)}}%
  %% slanting a path
  %% {##1} = {ycoord, slant}
  \newdef\slantpath##1{\@closmac{xslantedpath(##1)}}%
  \newlet\xslantpath\slantpath
  %% slanting a path
  %% {##1} = {xcoord, slant}
  \newdef\yslantpath##1{\@closmac{yslantedpath(##1)}}%
  %% reflecting a path
  %% {##1} = {point, point}
  \newdef\reflectpath##1{\@closmac{reflectedpath(##1)}}%
  \newdef\xyswappath{\@closmac{xyswappedpath}}%
  %
  %% Connecting two or more open figures:
  \newdef\connect{%
    \@figmac{begingroup}%
    \mfsrc{save nexus;}%
    \patharr{nexus}%
  }%
  \newdef\endconnect{%
    \endpatharr
    \mfsrc{mkpoly (false, nexus)}%
    \mfsrc{endgroup;}%
    \mfsrc{}%
    \ifin@latex
      \def\mfptmp@a{connect}%
      \ifx\mfptmp@a\@currenvir
        \aftergroup\@startfigtrue
        \aftergroup\@imrendtrue
        \@ignoretrue
      \fi
    \fi
    \ignorespaces
  }%
  %
  %% Affine transforms of the Metafont _coordinate system_ :
  % Grouping macros that enable nested coordinate systems:
  \newdef\coords{\mfsrc{}\mfsrc{bcoords}\mfsrc{}}%
  \newdef\endcoords{\mfsrc{}\mfsrc{ecoords}\mfsrc{}}%
  %% Macro that applies a nominated Metafont affine transformer:
  \newdef\applyT##1{\mfsrc{hide(apply_t(##1);)}}%
  %% Specific transform macros for Metafont coordinates;
  % See _The Metafontbook_ for most of these.
  % (\def, so ConTeXt won't cause a warning)
  \def\rotate##1{\applyT{rotated ##1}}% degrees
  \newdef\rotatearound##1##2{\applyT{rotatedaround(##1, ##2)}}% point, degrees.
  \newdef\@turn[##1]##2{\rotatearound{##1}{##2}}% point, degrees.
  \newdef\turn{\do@ptparam{@turn}{(0,0)}}%
  \newdef\reflectabout##1##2{\applyT{reflectedabout(##1,##2)}}% line ##1--##2.
  % (\let, so ConTeXt won't cause a warning)
  \let\mirror=\reflectabout
  \newdef\shift##1{\applyT{shifted ##1}}% pair.
  % (\def, so ConTeXt won't cause a warning)
  \def\scale##1{\applyT{scaled ##1}}% same scaling in X and Y directions.
  \newdef\xscale##1{\applyT{xscaled ##1}}% scale only X.
  \newdef\yscale##1{\applyT{yscaled ##1}}% scale only Y.
  \newdef\zscale##1{\applyT{zscaled ##1}}% complex multiplication of points.
  \newdef\xslant##1{\applyT{xslant ##1}}% skew in X direction by a multiple of Y coord.
  \newdef\yslant##1{\applyT{yslant ##1}}% skew in Y direction by a multiple of X coord.
  \newdef\zslant##1{\applyT{zslant ##1}}% see `grafbase.mf'.
  \newdef\boost##1{\applyT{boost ##1}}% special relativity boost.
  \newdef\xyswap{\applyT{xyswap}}% reflect in line Y=X.
  %%%%%%%%%%%%%%%%%%%%%%%%%%
  %% End of Prefix commands.
  %%%%%%%%%%%%%%%%%%%%%%%%%%%
  % Actual paths and figures.
  %
  %% Axes
  %% [##1] = [dimension], defaults to [\the\axisheadlen]
  \newdef\@axes[##1]{%
    \mfsrc{}\mfsrc{axes(##1);}%
  }%
  \newdef\@xaxis[##1]{%
    \mfsrc{}\mfsrc{xaxis(##1);}%
  }%
  \newdef\@yaxis[##1]{%
    \mfsrc{}\mfsrc{yaxis(##1);}}%
  \newdef\xaxis{\do@ptparam{@xaxis}{\the\axisheadlen}}%
  \newdef\yaxis{\do@ptparam{@yaxis}{\the\axisheadlen}}%
  \newdef\axes{\do@ptparam{@axes}{\the\axisheadlen}}%
  %%  Border axes
  \newdef\axis{\alt@ptparam{\@axis}{\@@axis}}%
  \newdef\@axis[##1]##2{\@figmac{axis.##2(##1)}}%
  \newdef\@@axis##1{%
    \edef\@param{%
      \ifnum`##1<`x%
        \the\sideheadlen
      \else
        \the\axisheadlen
      \fi
    }%
    \@axis[\@param]{##1}%
  }%
  \newdef\doaxes{\alt@ptparam{\@doaxes}{\@@doaxes}}%
  \newdef\@doaxes[##1]##2{%
    \def\mfp@axis{\@axis[##1]}%
    \do@axis##2\mfp@delim}%
  \newdef\@@doaxes##1{%
    \def\mfp@axis{\@@axis}%
    \do@axis##1\mfp@delim}%
  \newdef\do@axis##1{%
    \ifx\mfp@delim##1
    \else\mfp@axis{##1}\@xp\do@axis
    \fi
  }%
  %
  %% Axes marks
  %% [##1] = [dimension], defaults to [\the\hashlen]
  %%         followed by a list of x- or y-values (read later)
  \newdef\@marks[##1]{%
    \mfsrc{}\mfsrc{\mfp@axisletter marks(##1)}\mfp@writedata}%
  %%  ##1  = axis letter (passed by \xaxis, etc.)
  \newdef\axismarks##1{%
    \def\mfp@axisletter{##1}\do@ptparam{@marks}{\the\hashlen}}%
%
  \newdef\xmarks{\axismarks x}%
  \newdef\ymarks{\axismarks y}%
  %% Border axes marks
  \newdef\lmarks{\axismarks l}%
  \newdef\bmarks{\axismarks b}%
  \newdef\rmarks{\axismarks r}%
  \newdef\tmarks{\axismarks t}%
  %% Grid: actually a lattice of points
  %% [##1] = [<dimen>], diameter of points
  %% {##2} = {number, number}, horizontal,vertical spacing
  % (\def, so ConTeXt won't cause a warning)
  \def\grid{\do@ptparam{@grid}{0.5pt}}%
  \newdef\@grid[##1]##2{%
    \mfsrc{vgrid(##1)(##2);}%
  }%
  \newlet\gridpoints=\grid
  \newlet\lattice=\grid
  %% grid of lines
  %% ##1 = {number,number}, horizontal,vertical spacing
  \newdef\gridlines##1{%
    \mfsrc{}\mfsrc{gridlines(##1);}%
  }%
  %% polar grid of radii and arcs, clipped to picture rectangle.
  %% ##1 = {number,number}, arc spacing, number of radii
  \newdef\plrgrid##1{%
    \mfsrc{}\mfsrc{polargrid(##1);}%
  }%
  %% Polar patch of radii and arcs: a patch bounded by two arcs and
  %% two radii. Not clipped.
  %% ##1 = {num,num,num,num,num,num} specifying starting radius,
  %% ending radius, step size of radius, starting angle, ending angle,
  %% step size of angle.
  \newdef\plrpatch##1{%
    \mfsrc{}\mfsrc{polarpatch(##1);}%
  }%
  %% Points (filled disks) :
  %% [##1] = [dimension], defaults to \the\pointsize
  %%  A list of points should follow.
  \newdef\@point[##1]{%
    \mfsrc{}\mfsrc{pointd(##1,\ifpointfill true\else false\fi)}\mfp@writedata}%
  \newdef\point{\do@ptparam{@point}{\the\pointsize}}%
  %% "Points" with other shapes:
  %% [##1] = [dimension], defaults to \the\pointsize
  %%  ##2  = Metafont variable, the name of the shape, as in \plot
  %%  A list of points should follow.
  \newdef\@plotsymbol[##1]##2{%
    \mfsrc{}\mfsrc{plotsymbol(##2,##1)}\mfp@writedata}%
  \newdef\plotsymbol{\do@ptparam{@plotsymbol}{\the\pointsize}}%
  %%  "Points" with text:
  %% [##1] = justification, as in \tlabel
  %%  ##2 = TeX text (intended to be a single letter or symbol)
  %%  ##3 = list of points
  \newdef\@plottext[##1]##2##3{%
    \tlabeljustify{##1}%
    \def\extra@tlabel{\@@plottext{##2}}%
    \@@plottext{##2}##3,\mfp@delim
  }%
  \newdef\@@plottext##1{%
    \mfp@ifnextchar\mfp@delim
      {\@firstoftwo\endgroup}% group begun in \plottext
      {\mfp@ifnextchar(%)
        {\@plottext@{##1}}{\@plottext@@{##1}}%
      }%
  }%
  \newdef\@plottext@##1(##2,##3),{\tlabel({##2},{##3}){##1}}%
  \newdef\@plottext@@##1##2,{\tlabel{##2}{##1}}%
  \newdef\plottext{\begingroup\catcode`\^^M=5
    \do@ptparam{@plottext}{cc}%
  }%
  %%%%%%%
  % Paths
  %
  %% \@polyline
  %% ##1 = true or false
  %% A list of points should follow
  \newdef\@polyline##1{%
    \@listmac{polyline(##1)}}%
  %% polyline (open) and polygon (closed) :
  \newdef\polyline{\@polyline{false}}%
  \newlet\lines=\polyline
  \newdef\polygon{\@polyline{true}}%
  %% A function from a list of points with monotone x coordinates:
  %% [##1] = "tension", numeric >= 1.
  %% A list of points should follow.
  \newdef\@fcncurve[##1]{%
    \@listmac{functioncurve(##1)}}%
  \newdef\fcncurve{\do@ptparam{@fcncurve}{1.2}}%
  %% A symbol at every path node.
  %% [##1] = size of symbol (default \pointsize)
  %% ##2 = symbol, as in \plotsymbol
  \newdef\plotnodes{\do@ptparam{@plotnodes}{\the\pointsize}}%
  \newdef\@plotnodes[##1]##2{%
    \@rendmac{plotnodes(##2, ##1)}%
  }%
  %% Upright rectangle:
  %% ##1 = pair of points, (opposite corners of the rectangle)
  \newdef\rect##1{%
    \@figmac{rect(##1)}%
  }%
  %% Curve (open) :
  %% ##1 = number (tension)
  %% A list of points should follow.
  \newdef\curve{\do@ptparam{@curve}{1}}%
  \newdef\@curve[##1]{%
    \@listmac{tcurve(##1, false)}}%
  %% Cyclic curve (closed) :
  %% ##1 = number (tension)
  %% A list of points should follow.
  \newdef\cyclic{\do@ptparam{@cyclic}{1}}%
  \newdef\@cyclic[##1]{%
    \@listmac{tcurve(##1, true)}}%
  %% Open Quadratic B-splines
  %% A list of points should follow.
  \newdef\qspline{\@listmac{openqbs}}%
  %% Closed Quadratic B-splines
  %% A list of points should follow.
  \newdef\closedqspline{\@listmac{closedqbs}}%
  %% Open Cubic B-splines
  %% A list of points should follow.
  \newdef\cspline{\@listmac{opencbs}}%
  %% Closed Cubic B-splines
  %% A list of points should follow.
  \newdef\closedcspline{\@listmac{closedcbs}}%
  %% Circle
  %% ##1 = {point,number}, center and radius
  % (\def, so LaTeX won't cause a warning)
  \def\circle##1{\@figmac{circle(##1)}}%
  %% Ellipse
  %% [##1] = [number], angle of rotation, defaults to 0
  %% ##2 = {point, number, number}, center, x-radius, y-radius
  \newdef\@ellipse[##1]##2{%
    \@figmac{ellipse(##2, ##1)}%
  }%
  \newdef\ellipse{\do@ptparam{@ellipse}{0 deg}}%
  %% Circular Arc:
  %% ##1 = s, t, p or c, defaults to s
  \newdef\@arc[##1]##2{%
    %% ##2 = {point,point,point}, three points
    \if t##1\relax\@figmac{arcppp(##2)}\else
    %% ##2 = {point,number,number,number}, center, two angles and radius
    \if p##1\relax\@figmac{arcplr(##2)}\else
    %% ##2 = {point,point,number}, center, starting point, and angle
    \if c##1\relax\@figmac{arccps(##2)}\else
    %% ##2 = {point, point, angle}, endpoints and included angle
                  \@figmac{arcpps(##2)}%
    \fi\fi\fi
  }%
  \newdef\arc{\do@ptparam{@arc}{s}}%
  % Polar coordinates:
  \newdef\plr##1{map(polar)(##1)}%
  %% `Turtle graphics':
  %% A list of vectors should follow.
  \newdef\turtle{\@listmac{turtle}}%
  %% Sector of a circular region:
  %% ##1 = {point,number,number,number}, center, radius, and two angles
  \newdef\sector##1{\@figmac{sector(##1)}}%
  % Charts:
  % Pie chart
  % ##1 is a switch: c for clockwise, a for anticlockwise
  % ##2 is an angle: where the first wedge starts.
  %%  A list of numbers should follow.
  \def\piechart{\do@ptparam{@piechart}{c90}}%
  \def\@piechart[##1]{%
    \do@mtparam{##1}{##1}{c90}\@@piechart
  }%
  \def\@@piechart[##1##2]##3{%
    \mfsrc{}%
    \mfsrc{piechart(\if a##1 \else-\fi 1, %
        \if$##2$90\else ##2\fi, ##3)}\mfp@writedata}%
  \newdef\piewedge{\do@ptparam{@piewedge}{d}}%
  \newdef\@piewedge[##1]{\do@mtparam{##1}{##1}d\@@piewedge}%
  \newdef\@@piewedge[##1##2]##3{%
    \@figmac{%
    \if x##1 (piewedge[##3] shifted (##2*piedirection[##3]))%
    \else\if s##1 (piewedge[##3] shifted (##2))%
    \else\if m##1 (piewedge[##3] shifted (##2 - piecenter))%
    \else (piewedge[##3])%
    \fi\fi\fi}%
  }%
  % Bar chart
  \newdef\barchart{\do@ptparam{@barchart}{0,1,1}}%
  \newdef\@barchart[##1]##2{%
    \mfsrc{}%
    \mfsrc{barchart(##1,\if h##2 false\else true\fi)}\mfp@writedata}%
  \newdef\chartbar##1{\@figmac{chartbar[##1]}}%
  %% Function Plots:
  %% [##1##2] = [s<tens>] or [p], "smooth" or "polygon"
  %%  ##3 = {number,number,number}, start, finish, stepsize.
  %%  ##4 = legal Metafont numeric expression with x the only unknown
  \newdef\@function[##1]{\do@mtparam{##1}{##1}s\@@function}%
  \newdef\@@function[##1##2]##3##4{%
    \@figmac{tfunction(%
      \if p##1false\else true\fi,\if$##2$1\else ##2\fi)(##3)(##4)}}%
  \newdef\function{\do@ptparam{@function}{s}}%
  %
  %% Parametric function:
  %% ##1, ##2 and ##3 as in \function
  %% ##4 = legal Metafont pair expression with t the only unknown
  \newdef\@parafcn[##1]{\do@mtparam{##1}{##1}s\@@parafcn}%
  \newdef\@@parafcn[##1##2]##3##4{%
    \@figmac{tparafcn (%
      \if p##1false\else true\fi,\if$##2$1\else##2\fi) (##3) (##4)}}%
  \newdef\parafcn{\do@ptparam{@parafcn}{s}}%
  %% Polar function
  %% ##1, ##2 and ##3 as in \function
  %% ##4 = legal Metafont numeric expression with t the only unknown
  %%       (t is interpreted as an angle in degrees)
  \newdef\@plrfcn[##1]{\do@mtparam{##1}{##1}s\@@plrfcn}%
  \newdef\@@plrfcn[##1##2]##3##4{%
    \@figmac{tplrfcn (%
      \if p##1false\else true\fi,\if$##2$1\else ##2\fi) (##3) (##4)}}%
  \newdef\plrfcn{\do@ptparam{@plrfcn}{s}}%
  %% Region between two functions
  %% ##1, ##2, ##3 and ##4 as in \function
  %% ##5 = another Metafont numeric expression with x the only unknown
  \newdef\@btwnfcn[##1]{\do@mtparam{##1}{##1}p\@@btwnfcn}%
  \newdef\@@btwnfcn[##1##2]##3##4##5{%
    \edef\@firstparams{\if s##1true\else false\fi,\if$##2$1\else ##2\fi}%
    \@figmac{((tfunction (\@firstparams) (##3) (##4))
      --(reverse tfunction (\@firstparams) (##3) (##5))
      --cycle)}}%
  \newdef\btwnfcn{\do@ptparam{@btwnfcn}{p}}%
  %% Region swept out by a polar function
  %% ##1, ##2, and ##3 as in \plrfcn
  \newdef\@plrregion[##1]{\do@mtparam{##1}{##1}p\@@plrregion}%
  \newdef\@@plrregion[##1##2]##3##4{%
    \@figmac{(tplrfcn (%
      \if s##1true\else false\fi,\if$##2$1\else ##2\fi) (##3) (##4)
        --(0,0)--cycle)}}%
  \newdef\plrregion{\do@ptparam{@plrregion}{p}}%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %% End of actual paths and figures
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  \newdef\fdef##1##2##3{%
    \mfsrc{}%
    \mfsrc{vardef ##1 (expr ##2) =}%
    \mfsrc{##3}%
    \mfsrc{enddef;}%
  }%
  \mfp@additions
  %% End define mfpic drawing macros.
  %%
}%
%%%
%%% End of \@mfpic@graf@macs Definition.
%%%
% Set up default tlabel justification...
% (Default rotation is empty rather than 0 so
%  we don't generate a complaint under metafont option.)
\newcount\tl@vpos
\tl@vpos=-1
\newcount\tl@hpos
\tl@hpos=-1
\newdef\tlabel@rot{}%   default rotation   (none)
% ...and mechanism for changing it
\newdef\tlabeljustify#1{%
  \if$#1$\else  % empty: do nothing
    \mfp@justify#1\mfp@delim
  \fi}%
\newdef\mfp@justify#1#2\mfp@delim{%
  \if$#2$\mfp@setvpos{#1}\else
    \@mfp@justify#1#2\mfp@delim
  \fi
}%
\newdef\@mfp@justify#1#2#3\mfp@delim{%
  \mfp@setvpos{#1}%
  \mfp@sethpos{#2}%
  \edef\tlabel@rot{#3}%
}%
\newdef\mfp@setvpos#1{% -1 for default
  \if B#1\tl@vpos=-1 \else
  \if b#1\tl@vpos=0 \else
  \if c#1\tl@vpos=1 \else
  \if t#1\tl@vpos=2 \else
    \mfp@justifyerror\tl@vpos=-1
  \fi\fi\fi\fi
}%
\newdef\mfp@sethpos#1{% -1 for default
  \if l#1 \tl@hpos=-1 \else
  \if c#1 \tl@hpos=0 \else
  \if r#1 \tl@hpos=1 \else
    \mfp@justifyerror\tl@hpos=-1
  \fi\fi\fi
}%
\newdef\mfp@justifyerror{%
    \mfp@errmsg
     {Invalid justification parameter for text labels.}%
     {The optional argument for a text label must be^^J
      one of B, b, c or t followed by one of l, c, or r,^^J
      optionally followed by an angle of rotation.}%
}%
% Uniform adjustments in tlabels:
% (even metafont needs these to position \tlabeloval, etc.)
% #1 is horizontal offset, #2 vertical, both in _graph_ coordinates
\newdef\tlabeloffset#1#2{%
  \tlabel@hadj=#1\relax
  \tlabel@vadj=#2\relax
  \set@mfvariable{pair}{label_adjust}{(\the\tlabel@hadj,\the\tlabel@vadj)}%
}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Beginning of mfpic environment:
%%%
%% #1 = xscale, #2 = yscale, #3 = xmin, #4 = xmax
%% #5 = ymin, #6 = ymax
\newdef\@mfpic#1#2#3#4#5#6%
{%% Save mfpic's extra fontdimen values to make them local:
  \save@mfpicdimens
  % save font current at start of environment
  \font\@tcurr=\fontname\font\relax
  \begingroup % ended near end of \endmfpic
  \let\par\relax
  % Change to null font for duration of mfpic environment.
  \nullfont
  % Plain TeX setting for paragraph's `finishing glue' (TeXbook, p 100).
  \parfillskip0pt plus1fil\relax
  % Define mfpic graphics macros.
  \@mfpic@graf@macs
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % Local conversion of a dimension control sequence ##1 :
  % (TeX won't \advance a font dimension.)
  \newdef\@xconv##1{%
   {\mfp@scratch = ##1\relax
    \advance\mfp@scratch by -#3\mfpicunit
    \mfp@scratch = #1\mfp@scratch
    \advance\mfp@scratch -\mfpicllx bp
    \global ##1 = \mfp@scratch}%
  }%
  \newdef\@yconv##1{%
   {\mfp@scratch=##1\relax
    \advance\mfp@scratch by -#5\mfpicunit
    \mfp@scratch = #2\mfp@scratch
    \advance\mfp@scratch -\mfpiclly bp
    \global ##1 = \mfp@scratch}%
  }%
  %%%%%%%%%%%%%%%%%%%
  % Set up Graph Box:
  %
  % Dimensions set below may be changed under metapost
  \@graphright=#4\mfpicunit \@xconv\@graphright
  \@graphht=#6\mfpicunit \@yconv\@graphht
  \global\@graphwd=\@graphright
  %
  %%%%%%%%%%%%%%%%%%
  % Typeset picture.
  \global\setbox\@wholegraph=%
  \ifmfpicdraft
    \vbox{% unvboxed in \@tlabel
      \vbox to \@graphht{\vss
        \hbox to \@graphwd{\kern2pt\tt\#\number\mfp@count\hss}%
        \kern2pt
      }%
    }%
  \else
    \vbox{% unvboxed in \@tlabel                        %Kuben
      \if@mfp@metapost
        \vbox
      \else
        \vbox to \@graphht
      \fi
      {%
        \vss
        \edef\@graphfilename{\setfilename{\mfp@filename}{\number\mfp@count}}%
        \if@mfp@metapost
          \openin\mfp@graph=\@graphfilename\relax
          \ifeof\mfp@graph
            \MFpic@msg{No graph file: \@graphfilename\space.}%
            \def\@setmfpicgraphic##1{\raise2pt\hbox{\kern2pt\tt ##1}}%
            \closein\mfp@graph
          \else
            \ifin@LaTeXe
              \@namedef{Gin@rule@.\number\mfp@count}##1{%
                {\mfp@Gtype}{.\number\mfp@count}{##1}%
              }%
            \fi
          \fi
        \fi
        \if@mfp@metapost
          \hbox
        \else
          \hbox to \@graphwd
        \fi
          {\@xp\@setmfpicgraphic\@xp{\@graphfilename}\hss}% End hbox.
        \kern0pt\relax
      }% End vbox
    }% End vbox
  \fi
  \if@mfp@metapost
    \@graphright=\wd\@wholegraph
    \@graphht=\ht\@wholegraph
    \global \@graphwd=\@graphright
  \fi % Otherwise setting has already been done
  \@graphleft=0pt
  \@graphdp=0pt
  % Set up Metafont file:
  \mfsrc{}%
  \mfsrc{unitlen:=\the\mfpicunit\mf@s;}%
  \mfsrc{xscale:=#1; yscale:=#2;}%
  \mfsrc{xneg:=#3; xpos:=#4;}%
  \mfsrc{yneg:=#5; ypos:=#6;}%
  \mfsrc{\mf@p}%
  % The following should make it easier to keep figure numbers in sync
  \mfsrc{beginmfpic(\number\mfp@count);\mf@p\space\@mfplineno.}%
  \if@mfp@mplabels
    \mfsrc{verbatimtex}%
    \mfsrc{\space\begingroup\font\noexpand\MFPcfont=\fontname\@tcurr}%
    \mfsrc{etex}%
  \fi
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % (TeX/MP based) labels and caption:
  \newdef\mfp@btex##1{btex \noexpand\MFPtext{##1} etex}%
  \newdef\extra@tlabel{}%
  %%%%%%%%
  % Labels in metapost:
  % ##1 = (list of) pair expression(s)
  % ##2 = horizontal mode material (label's text).
  %
  \newdef\@@tlabel##1##2{%
  \mfp@toks{##2}%
  % Horizontal position of reference point is given by the
  % first two parameters of gblabel: l=1,0  c=.5,.5  r=0,1
  % Vertical position uses next two:
  % t=0,1      | Explanation: if params are (a,b,c,d) we compute
  % c=.5,.5    | the coordinates of a new reference point
  % B=0,0      | (a*left+b*right, c*bot+d*top). E.g., center is
  % b=1,0      | average of left and right, top and bottom.
  \edef\mfp@pos{% horizontal:
    \ifcase\tl@hpos .5,.5\or 0,1\else 1,0\fi
    ,% vertical:
    \ifcase\tl@vpos 1,0\or .5,.5\or 0,1\else 0,0\fi
  }%
  \edef\mfp@rot{\if$\tlabel@rot$0\else\tlabel@rot\fi}%
  \mfsrc{gblabel(\mfp@pos,\mfp@rot)(\mfp@btex{\the\mfp@toks})(##1);}%
  \endgroup % begun in \tlabel
  \extra@tlabel
  }%
  % Labels in TeX
  % ##1 = x-coordinate
  % ##2 = y-coordinate
  % ##3 = horizontal mode material, labels's text.
  %
  \newdef\@tlabel##1##2##3{%
    %
    % Compute width of graph with label (##3):
    %
    \setbox\@textbox=%
      \vbox{\def\\{\cr}\mfp@restorepar
        \@tcurr\the\every@tlabel
        \halign{####\hfil\cr##3\crcr}%
      }%
    \if$\tlabel@rot$\else
      \MFpic@msg%
        {Rotation parameter "\tlabel@rot" ignored in \string\tlabel\on@line .}%
    \fi
    %
    % Stretch Graph Rightward:
    %
    \mfp@scratch=##1\mfpicunit
    \@xconv\mfp@scratch
    \begingroup
    \ifcase\tl@hpos % center
      \advance\mfp@scratch 0.5\mfp@tbwd
    \or             % right
      \advance\mfp@scratch -\tlabel@sep
    \else           % left or invalid
      \advance\mfp@scratch \mfp@tbwd
      \advance\mfp@scratch \tlabel@sep
    \fi
    \advance\mfp@scratch \tlabel@hadj
    \ifdim \mfp@scratch>\@graphright
      \global\@graphright=\mfp@scratch
    \fi
    \endgroup
    %
    % Stretch Graph Leftward:
    %
    \begingroup
    \ifcase\tl@hpos % center
      \advance\mfp@scratch -0.5\mfp@tbwd
    \or             % right
      \advance\mfp@scratch -\mfp@tbwd
      \advance\mfp@scratch -\tlabel@sep
    \else           % left or invalid
      \advance\mfp@scratch \tlabel@sep
    \fi
    \advance\mfp@scratch \tlabel@hadj
    \ifdim \mfp@scratch<\@graphleft
      \global\@graphleft=\mfp@scratch
    \fi
    \endgroup
    %
    % Stretch Graph Upward:
    %
    \mfp@scratch=##2\mfpicunit
    \@yconv\mfp@scratch
    \begingroup
    \ifcase\tl@vpos %bottom
      \advance\mfp@scratch \mfp@tbht
      \advance\mfp@scratch \mfp@tbdp
      \advance\mfp@scratch \tlabel@sep
    \or             % center
      \advance\mfp@scratch 0.5\mfp@tbht
      \advance\mfp@scratch 0.5\mfp@tbdp
    \or             % top
      \advance\mfp@scratch -\tlabel@sep
    \else           % baseline or invalid
      \advance\mfp@scratch \mfp@tbht
    \fi
    \advance\mfp@scratch \tlabel@vadj
    \ifdim \mfp@scratch>\@graphht
      \global\@graphht=\mfp@scratch
    \fi
    \endgroup
    %
    % Stretch Graph Downward:
    %
    \begingroup
    \ifcase\tl@vpos % bottom
      \advance\mfp@scratch \tlabel@sep
    \or             % center
      \advance\mfp@scratch -0.5\mfp@tbht
      \advance\mfp@scratch -0.5\mfp@tbdp
    \or             % top
      \advance\mfp@scratch -\mfp@tbht
      \advance\mfp@scratch -\mfp@tbdp
      \advance\mfp@scratch -\tlabel@sep
    \else           % baseline or invalid
      \advance\mfp@scratch -\mfp@tbdp
    \fi
    \advance\mfp@scratch \tlabel@vadj
    \ifdim \mfp@scratch<\@graphdp
      \global \@graphdp=\mfp@scratch
    \fi
    \endgroup
    %
    % Set label onto graph:
    %
    \global\setbox\@wholegraph=%
      \vtop{\unvbox\@wholegraph
        \vbox to0pt{%
          \ifcase\tl@vpos % bottom
            \kern-\mfp@tbht \kern-\mfp@tbdp
            \kern-\tlabel@sep
          \or             % center
            \kern-0.5\mfp@tbht \kern-0.5\mfp@tbdp
          \or             % top
            \kern\tlabel@sep
          \else           % baseline or invalid
            \kern-\mfp@tbht
          \fi
          %\mfp@scratch=##2\mfpicunit % already done
          %\@yconv\mfp@scratch        % already done
          \kern-\mfp@scratch
          \kern-\tlabel@vadj
          \hbox{%
            \ifcase\tl@hpos % center
              \kern-0.5\mfp@tbwd
            \or             % right
              \kern-\mfp@tbwd
              \kern-\tlabel@sep
            \else           % left or invalid
              \kern\tlabel@sep
            \fi
            \mfp@scratch=##1\mfpicunit
            \@xconv\mfp@scratch
            \kern\mfp@scratch
            \kern\tlabel@hadj
            \box\@textbox }% End hbox.
          \vss}% End vbox.
        }% End vtop.                                                  %Kuben
    \endgroup %begun in \tlabel
    \extra@tlabel
  }% -- End \@tlabel
  %%%%%%%%%%%
  % Generic labels (TeX or MetaPost)
  % [##1] = justification and rotation
  % followed by either
  %     (x,y) of {(x,y)} or {<pair-expression>}
  % and then label text.
  \newdef\tlabel{%
    % Hide changes made by \tlabeljustify and redef of \tlabel@rot:
    \begingroup    % ended in \@(@)tlabel
    \catcode`\^^M=5 % newlines in TeX code not handled correctly
                    % by some versions of MetaPost
    %  So only specified rotation will cause warning:
    \if@mfp@mplabels\else\def\tlabel@rot{}\fi
    \alt@ptparam{\@tlabel@}{\@tlabel@@}}%
  %
  % Using \tlabeljustify guards against empty optional parameter,
  % as well as simplifying later commands by passing the justification
  % as integers \tl@hpos, etc.
  \newdef\@tlabel@[##1]{\tlabeljustify{##1}\@tlabel@@}%
  %
  % Check for "(.., ..)":
  \newdef\@tlabel@@{%
    \mfp@ifnextchar(%)
      {\@@tlabel@}{\@@tlabel@@}%
  }%
  %
  % Old style parameters, (x,y):
  % ##1 = x-coordinate
  % ##2 = y-coordinate
  \newdef\@@tlabel@(##1,##2){%
    \if@mfp@mplabels\@xp\@firstoftwo\else\@xp\@secondoftwo\fi
    {\@@tlabel{(##1,##2)}}{\@tlabel{##1}{##2}}}%
  %
  % New possibility:
  % {##1} = {<list of pair-expressions>}
  \newdef\@@tlabel@@##1{%
    \if@mfp@mplabels\@xp\@firstoftwo\else\@xp\@secondoftwo\fi
    % for mplabels pass point(s) as single parameter
    {\@@tlabel{##1}}%
    % for nomplabels, strip braces and assume parentheses inside:
    {\@@tlabel@##1}}%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % \tlabel@path produces a path surrounding given text
  % ##1      selects the type of path: rect, oval, or ellipse.
  % ##2      is the default value of an optional argument modifying the
  %          shape of the path (radius of rounding, default=0pt;
  %          stretching factor for \tlabeloval and ratio of axes for
  %          \tlabelellipse, defaults=1).
  % ##3,##4  give location ([cc] justification only).
  % ##5      is text to place. TeX measures the text and passes the info
  %          to MF, except in case of mplabels.
  %
  % Draws the path and sets the label, the star form only draws the
  % path.
  %
  \newdef\tlabel@path##1##2{%
    \def\mfp@parami{##1}\def\mfp@paramii{##2}%
    \mfp@ifnextchar*%
      {\@mfp@star@true\@firstoftwo\@tlabelpath}% gobbles the star
      {\@mfp@star@false\@tlabelpath}%
  }%
  \newdef\@tlabelpath{%
    \do@ptparam{@@tlabelpath}{\mfp@paramii}%
  }%
  \newdef\@@tlabelpath[##1]{%
    \mfp@ifnextchar(%)
      {\@@tlabelpath@{##1}}%
      {\@@tlabelpath@@{##1}}%
  }%
  \newdef\@@tlabelpath@##1(##2,##3)##4{%
    \if@mfp@mplabels
      \mfp@toks={##4}%
      \@figmac{text\mfp@parami(\mfp@btex{\the\mfp@toks},##1,(##2,##3))}%
    \else
      \measure@textbox{##4}%
      \@figmac
        {text\mfp@parami((\the\mfp@tbwd,\the\mfp@tbht),##1,(##2,##3))}%
    \fi
    \if@mfp@star@\else
      \tlabel[cc]({##2},{##3}){##4}%
    \fi
  }%
  \newdef\@@tlabelpath@@##1##2##3{%
    \if@mfp@mplabels
      \mfp@toks={##3}%
      \@figmac{text\mfp@parami(\mfp@btex{\the\mfp@toks},##1,##2)}%
    \else
      \measure@textbox{##3}%
      \@figmac
        {text\mfp@parami((\the\mfp@tbwd,\the\mfp@tbht),##1,##2)}%
    \fi
    \if@mfp@star@\else
        \tlabel[cc]{##2}{##3}%
    \fi
  }%
  % the next four simply call \tlabel@path
  \newdef\tlabelrect{\tlabel@path{rect}{0pt}}%
  \newdef\tlabeloval{\tlabel@path{oval}{1}}%
  \newdef\tlabelellipse{\tlabel@path{ellipse}{1}}%
  \newlet\tlabelcircle\tlabelellipse
  \newdef\measure@textbox##1{%
    \setbox\@textbox=%
      \vbox{\def\\{\cr}\mfp@restorepar
        \@tcurr\the\every@tlabel
        \halign{####\hfil\cr##1\crcr}%
        \kern0pt % Avoid having to add the depth of \@textbox
      }%
  }%
  % Proceedure for doing multiple tlabels in one command:
  %
  \newdef\tlabels{% Change catcodes, then read argument
    \begingroup
    \catcode`\^^M=5
    \@tlabels
  }%
  \newdef\@tlabels##1{% Read argument, then set up start of loop.
    % hook at end of \tlabel implements iteration.
    \def\extra@tlabel{\do@tlabels}%
    \do@tlabels##1\mfp@delim
  }%
  \newdef\do@tlabels{%
    \mfp@ifnextchar\mfp@delim{\@firstoftwo\endgroup}{\tlabel}%
  }%
  %
  \newdef\axislabels##1{%
   \begingroup
   \catcode`\^^M=5
   %% initialize:
   \let\mfp@xcoord=\mfp@identy
   \let\mfp@ycoord=\mfp@identy
   \def\tlabel@vpos{c}%
   \def\tlabel@hpos{c}%
   \def\tlabel@rot{}%
   % default justification and axis origin depend on axis:
   \if y##1\relax
     \def\tlabel@hpos{r}\def\mfp@xcoord{0}%
   \else\if l##1\relax
     \def\tlabel@hpos{r}\edef\mfp@xcoord{\mfp@lshift}%
     \mfp@addto\mfp@xcoord{#3}%
   \else\if b##1\relax
     \def\tlabel@vpos{t}\edef\mfp@ycoord{\mfp@bshift}%
     \mfp@addto\mfp@ycoord{#5}%
   \else\if r##1\relax
     \def\tlabel@hpos{l}\edef\mfp@xcoord{-\mfp@rshift}%
     \mfp@addto\mfp@xcoord{#4}%
   \else\if t##1\relax
     \def\tlabel@vpos{b}\edef\mfp@ycoord{-\mfp@tshift}%
     \mfp@addto\mfp@ycoord{#6}%
   \else\if x##1\relax
     \def\tlabel@vpos{t}\def\mfp@ycoord{0}%
   \else
     \def\tlabel@vpos{t}\def\mfp@ycoord{0}%
     \mfp@errmsg
      {Invalid argument to \string\axislabels!}%
      {The first argument of \axislabels must be one of the following^^J%
       single letters: x, y, l, b, r, or t. If you proceed, x will be^^J%
       assumed.}%
   \fi\fi\fi\fi\fi\fi
   % After the following, (\mfp@xcoord{num},\mfp@ycoord{num}) are
   % coordinates of num on given axis:
   \ifx\mfp@identy\mfp@xcoord
     \edef\mfp@ycoord####1{\mfp@ycoord}%
   \else
     \edef\mfp@xcoord####1{\mfp@xcoord}%
   \fi
   % now do the labels,
   \do@ptparam{@axislabels}{\tlabel@vpos\tlabel@hpos\tlabel@rot}%
  }%
  \newdef\@axislabels[##1]##2{%
    \tlabeljustify{##1}%
    \do@axislabel##2,\mfp@delim,%
  }%
  % ##1 is text, ##2 is number
  \newdef\do@axislabel##1##2,{%
    \ifx\mfp@delim##1\let\mfp@next\endgroup
    \else\ifx\mfp@delim##2\mfp@delim % comma within pair? Reread ##2,
      \mfp@msg{}%
      \MFpic@warn%
        {Possible extra comma, forgotten point, or omitted braces %
            in \string\axislabels\on@line .}%
      \mfp@msg{}%
      \def\mfp@next{\do@axislabel{##1}}% Assume extra comma, read number
    \else
      \tlabel(\mfp@xcoord{##2},\mfp@ycoord{##2}){##1}%
      \def\mfp@next{\do@axislabel}% get next pair of arguments.
    \fi\fi\mfp@next
  }%
  %
  %%%%%%%%%%
  % Caption:
  %
  % \@docaption (called by \endmfpic)
  % Do nothing until \tcaption is used :
  \newdef\@docaption{}%                                               %Kuben
  %
  % Arg 1 meaning:  maxwd; see mfpicdoc.tex.
  % Arg 2 meaning:  linewd; see mfpicdoc.tex.
  % Arg 3 meaning:  caption's text.
  %
  \newdef\@tcaption[##1,##2]##3%
  {%
   % Redefine \@docaption to Set Caption:
   \redef\@docaption
   {%
    % Compute Adjustments to Center:
    % 1.  Measure caption text.
    %
    \setbox\@textbox=%
      % \\ forces \vbox option, then is redefined in the \vbox:
     \hbox{\def\\{\hskip\@m\p@}\mfp@restorepar
      \@tcurr##3}%
    % 2.  If caption text is so much wider than graph, then
    %     stretch graph box horizontally.
    \@graphwd=\wd\@wholegraph                      %Kuben
    \ifdim\mfp@tbwd>##1\@graphwd
     \@graphwd=##2\@graphwd
     \setbox\@textbox=%
      \hbox{%
       \vbox{%
        \ifin@latex\else  % keep LaTeX's \\
         \def\\{\unskip\hbox{}\hfil\penalty-\@M\ignorespaces}%
        \fi
        % Prevent \leftskip and \rightskip from interfering with
        % caption:
        \leftskip=0pt
        \rightskip=0pt
        \if@mfp@centercaptions
          \leftskip=0pt plus 0.5fil
          \rightskip=0pt plus -0.5fil
          \parfillskip=0pt plus 1fil
        \fi
        % 3. Here's where the graph box's width is adjusted.
        \hsize=\@graphwd
        % 4. Contribute the caption text,
        %    in a nonindented paragraph below the graph.
        \mfp@restorepar
        \noindent\@tcurr##3%
       }% End vbox.
      }% End hbox.
    \fi
    \mfp@scratch=\wd\@wholegraph
    \ifdim \mfp@tbwd>\mfp@scratch
      \mfp@scratch=\mfp@tbwd
    \fi
    % Set Caption onto Picture:
    \global\setbox\@wholegraph=%
     \vbox{%
       \hbox to \mfp@scratch{\hss\box\@wholegraph\hss}%
       \nointerlineskip\medskip
       \hbox to \mfp@scratch{\hss\box\@textbox\hss}%
     }% End vbox.
   }% -- End \@docaption.
   \ignorespaces
  }% -- End \@tcaption.
  %
  % \tcaption[maxwd,linewd]{text} :
  \newdef\tcaption{\do@ptparam{@tcaption}{1.2, 1.0}}%
  %
  % End of Object Macros.
  %\preservelines
  \ignorespaces
}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% End of \@mfpic Definition.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  Definition of \mfpic Command.
%
% \mfpic[xscale][yscale]{xneg}{xpos}{yneg}{ypos}
%
\newdef\mfpic{%
  \@if@mfp@beforefileopen
    {\nooutputfileerror{\mfpic}}%
    {\do@ptparam{mfpic@}{1}}%
  }%
\newdef\mfpic@[#1]{\alt@ptparam{\@pici{#1}}{\@mfpic{#1}{#1}}}%
\newdef\@pici#1[#2]{\@mfpic{#1}{#2}}%
%%%
%%% End of \mfpic Definition.
%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Definition of Closure of mfpic Environment:
%%%
\MFPdebugwrite{Definition of closure of mfpic environment.}%
\newdef\endmfpic
{%
  \mfsrc{}%
  \if@mfp@mplabels \mfsrc{verbatimtex \endgroup\space etex}\fi
  \mfsrc{endmfpic;\mf@p (\number\mfp@count) \space\@mfplineno.}%
  \mfsrc{}%
  \ifmfpicdebug
    \wlog{}%
    \wlog{MFpic: ENTERED endmfpic.}%
    \wlog{}%
  \fi
  \if@mfp@shipping % Don't set or save the picture, nor increment
                   % the counter, if no picture is being shipped out.
    \global \@graphwd=\@graphright
    \ifmfpicdebug
      \wlog{MFpic: graphleft  = \the\@graphleft}%
      \wlog{MFpic: graphright = \the\@graphright}%
      \wlog{MFpic: graphwd    = \the\@graphwd}%
      \wlog{MFpic: graphht    = \the\@graphht}%
      \wlog{MFpic: graphdp    = \the\@graphdp}%
      \wlog{}%
    \fi
    \mfp@scratch=\@graphht
    \advance\mfp@scratch by -\@graphdp
    \global\setbox\@wholegraph=%
      \vbox to \mfp@scratch{%
       \vss
       \hbox{\kern-\@graphleft\box\@wholegraph}%
       \kern-\@graphdp
      }% End vbox.
    \@docaption
    \ifmfpicdebug
      \wlog{MFpic: graphleft  = \the\@graphleft}%
      \wlog{MFpic: graphright = \the\@graphright}%
      \wlog{MFpic: graphwd    = \the\@graphwd}%
      \wlog{}%
      \wlog{MFpic: DONE endmfpic.}%
      \wlog{}%
    \fi
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Typesetting the graph, including labels and caption.
    %
    %  \s@vemfpic is only defined if \savepic was issued since
    %  the last \endmfpic...
    \mfpicheight\ht\@wholegraph
    \mfpicwidth\wd\@wholegraph
    \ifx\s@vemfpic\UndEfInEd
      \ifmfpicdraft % draw frame, box should contain only picture number
                    % and caption (plus any tlabels if not mplabels).
        \leavevmode\@mfpframed[-\mfpframethickness]{\box\@wholegraph}%
      \else
        \leavevmode\box\@wholegraph
      \fi
    \else
      % ... in which case \s@vemfpic expands to a box name...
      \ifmfpicdraft
        \global\setbox\s@vemfpic=%
          \hbox{\@mfpframed[-\mfpframethickness]{\box\@wholegraph}}%
      \else
        \global\setbox\s@vemfpic=\box\@wholegraph
      \fi
    \fi
    %  ...now require a new "\savepic\bar" to save next pic
    \global\let\s@vemfpic\UndEfInEd
    \global \advance\mfp@count1
  \fi % end of code skipped by \noship
  \endgroup % Begun near start of \@mfpic
  \restore@mfpicdimens
  \ifin@latex
    \def\mfptmp@a{mfpic}%
    \ifx\mfptmp@a\@currenvir
      \@ignoretrue
    \fi
  \fi
  \ignorespaces
}%
\newdimen\mfpicheight
\newdimen\mfpicwidth
%%%
%%% End of \endmfpic Definition.
%%%
%  \newsavepic just \newsavebox
\newdef\newsavepic#1{%
 \ifin@latex
  \newsavebox{#1}%
 \else
  \mfp@ifdefined{#1}%
   {\mfp@errmsg
    {Command \string #1 already defined (or improper).}%
    {You have used \newsavepic with an already defined or an^^J%
     improper control sequence. Replace #1 with another command or^^J%
     I will proceed with \newsavepic ignored.}}%
   {\csname newbox\endcsname#1}%
 \fi
}%
\let\newpic=\newsavepic % compatibility
\newdef\savepic#1{%
  \relax
  \mfp@ifdefined{#1}%
   {\gdef\s@vemfpic{#1}}%
   {\mfp@errmsg
    {Box \string#1 undefined.}%
    {You tried to save a picture in a box which had not been^^J%
     previously allocated. Use \newsavepic to allocate a box.}}%
}%
\newdef\usepic#1{%
  \relax
  \ifvoid#1
   \mfp@errmsg
    {Empty pic box!}%
    {You tried \usepic#1, but #1 is empty. Perhaps you misspelled it,^^J%
     or forgot the corresponding \savepic command.}%
    \leavevmode\hbox{}%
  \else
    \leavevmode\copy #1\relax
  \fi
}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Providing a frame around an mfpic
%
\newdimen\mfpframesep
\newdimen\mfpframethickness
\mfpframethickness0.4pt
\mfpframesep2pt
\newdef\mfpframed{\do@ptparam{@mfpframed}{\the\mfpframesep}}%
\mfp@ifdefined\framed
  {}{\let\framed=\mfpframed}%
\newdef\@mfpframed[#1]#2{\@mfpframe[#1]#2\endmfpframe}%
\newdef\mfpframe{\do@ptparam{@mfpframe}{\the\mfpframesep}}%
\newdef\@mfpframe[#1]{\leavevmode
  \hbox\bgroup
   \mfpframesep#1\relax
   \vrule width\mfpframethickness
   \vtop\bgroup
    \vbox\bgroup
     \hrule height\mfpframethickness
     \kern\mfpframesep
     \hbox\bgroup
      \kern\mfpframesep
      \ignorespaces
}%
\newdef\endmfpframe{\unskip
     \kern\mfpframesep
    \egroup
   \egroup
   \kern\mfpframesep
   \hrule height\mfpframethickness
  \egroup
  \vrule width\mfpframethickness
 \egroup
}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Simple utility for writing verbatimtex block
\newif\if@mfp@verbtex
\newtoks\mfp@verbtex
\newdef\mfpverbtex{%
  \begingroup
  \preservelines
  \catcode`\#=12  % \the\mfp@verbtex doubles normal # in \write
  \afterassignment\mfp@writetex
  \global\mfp@verbtex}%
\newdef\mfp@writetex{%
 \endgroup
 \@if@mfp@beforefileopen
  {\global\@mfp@verbtextrue}%
  {\if@mfp@metapost
   \mfsrc{verbatimtex}%
   \mfsrc{\the\mfp@verbtex}%
   \mfsrc{etex;}%
  \else
   \noMP@error{verbatimtex}%
  \fi
  \global\@mfp@verbtexfalse}%
}%
\global\mfp@count=1 % 1 because we now advance it in \endmfpic.
%%%
\MFPdebugwrite{Punctuation, etc., will revert to old catcodes now.}%
\MFPicpackagE%
%
\endinput%
