% Make @ active
\expandafter\xdef\csname c@tcode\endcsname{\the\catcode`@}
\catcode`\@=11

% A simple macro to check for undefined names
\def\ifundefined#1{\expandafter\ifx\csname #1\endcsname\relax}

% Have to define newlabel before we can input the .aux file
\def\newlabel#1#2{%
\ifundefined{ref.#1}%
	\expandafter\gdef\csname ref.#1\endcsname{#2}
\else
	% If it's undefined, then print a warning.
	\immediate\write16{WARNING: Multiply defined reference "#1"}
\fi
}

% File existence checkers
\newif\iffileexists
\def\testfileexistence#1{%
\begingroup
\immediate\openin0=#1
\ifeof 0%
\global\fileexistsfalse
\else
\global\fileexiststrue
\fi
\immediate\closein0
\endgroup}

% Allocate a stream number
\newwrite\reffilen@m

% We will want to know this later on.
\newif\ifauxfileexists

% Now input the symbols from the last time.
\testfileexistence{\jobname .aux}
\iffileexists
\expandafter\input\jobname .aux
\auxfileexiststrue
\else
\auxfileexistsfalse
\immediate\write16{WARNING:  .aux file not found.}
\immediate\write16{          No undefined reference warnings will be given.}
\fi

% Now open the file for output.
\immediate\openout\reffilen@m=\jobname.aux

% Make sure that *something* is in the .aux file.
\xdef\@gtempa{\write\reffilen@m{\string\relax}}\@gtempa

% Label takes two arguments: 1) the label name  2) the expansion text
\def\label#1#2{
\xdef\@gtempa{\write\reffilen@m{\string
\newlabel{#1}{#2}}}\@gtempa
}


% Ref takes the label name and replaces it with the expansion text.
\def\ref#1{%
\ifundefined{ref.#1}%
\ifauxfileexists
\immediate\write16{WARNING: Undefined reference: #1}%
\fi 
???%
\else
\csname ref.#1\endcsname
\fi
}

\catcode`\@=\c@tcode
