\newwrite\tocout
\def\lastsec{}
\newcount\subseccount
\newtoks\subsecs\subsecs={}
\def\toc{
    \maketoc
    \openout\tocout=bguide.toc
    \def\section##1{\makeoutline
        \def\lastsec{##1}
        \thesection{##1 \pdfdest name {##1} fit}
        \write\tocout{\noexpand\tocentry{##1}{\number\pageno}{0pt}}
    }
    \def\subsection##1{%
        \advance\subseccount by 1
        \subsecs=\expandafter{\the\subsecs\pdfoutline goto name {##1}{##1}}
        \thesubsection{##1 \pdfdest name {##1} fit}
        \write\tocout{\noexpand\tocentry{##1}{\number\pageno}{.5in}}
    }
}
\def\tocentry#1#2#3{%
    \count1=#2\advance\count1 by 1
    \line{\hskip#3%
    \pdfstartlink goto name {#1}
    {\color{red} #1}
    \pdfendlink
    \cleaders\hbox to .1in{\hfil .\hfil}\hfil #2}%
}
\def\thesection#1{#1}
\def\thesubsection#1{#1}
\def\section#1{\thesection{#1}}
\def\subsection#1{\thesubsection{#1}}
% temporary definitions for pre-toc sections
\def\maketoc{%
    \thesection{Table of Contents}

    \openin15=bguide.toc \ifeof15 \else
    \input bguide.toc\fi
    \closein15
}
\def\makeoutline{%
    \ifx\lastsec\empty\else\pdfoutline goto name
            {\lastsec} count \number\subseccount{\lastsec}
            \the\subsecs\subsecs={}\subseccount=0\fi
}
\def\fintoc{%
    \closeout\tocout
    \makeoutline
}
