\newcommand{\pic}{{\bf pic}}
\newcommand{\Pic}{{\bf Pic}}
\newcommand{\gpic}{{\bf gpic}}
\newcommand{\Gpic}{{\bf Gpic}}
\newcommand{\Dpic}{{\bf Dpic}}
\newcommand{\dpic}{{\bf dpic}}
\newcommand{\Mfour}{{\bf m4}}
  \tableofcontents
\section{Introduction}
   \begin{quotation}
   Before every conference, I find Ph.D.s in on weekends running back
   and forth from their offices to the printer.  It appears that people
   who are unable to execute pretty pictures with pen and paper find it
   gratifying to try with a computer \cite{Landauer95}.
   \end{quotation}

This document describes a set of macros, written in the \Mfour\ macro
language \cite{KRm4}, for producing electric circuits and other diagrams
in \LaTeX\ documents.  The macros evaluate to drawing commands in \pic,
a line-drawing language \cite{KRpic} which is readily available and
quite simple to learn.
The result is a system with the advantages and
disadvantages of \TeX\ itself, since it is macro-based and non-wysiwyg, and
since it uses ordinary character input.
The book from which the above quotation is taken correctly points out
that the payoff is in quality of diagrams, at the price of the time spent
in learning how to draw them.

A collection of basic components and conventions for their internal
structure are described.  For particular drawings it is often
convenient to create new macros, or combinations of them, using
consistent conventions, so macros such as these are only a starting
point.  The IEEE standard \cite{IEEEstd} has been followed.  The macros
described here make extensive use of the characteristics of \pic\ and have
been designed, where possible, to be an extension of the language.

\section{Using the macros}
The diagram source file is preprocessed as illustrated in
Fig.\ \ref{Flowdiag+}.  The source, together with the predefined
macros, is first passed through \Mfour, and then through a
\pic\ interpreter that produces a {\tt .tex} file to be inserted
into the {\tt .tex} source using the \verb|\input| command.

\begin{figure}[hbt]
   \input Flowdiag+
   \caption{Inclusion of figures and macros in the \LaTeX\ document}
   \label{Flowdiag+}
   \end{figure}

\noindent The {\tt .tex} file
contains, for example, {\bf tpic} specials, \LaTeX\ graphics,
or other graphics commands, such as for %{\bf mfpic} \cite{mfpic}, or
{\bf PSTricks} \cite{pstricks},
%or {\bf MetaPost} \cite{metapost}),
which \LaTeX\ will convert or include in a {\tt .dvi} file. The {\tt .dvi}
file is then to be viewed or printed by a driver capable of
interpreting any \verb|\special| commands inserted by the
\pic\ processor.

To convert \pic\ to TeX input one can use \cite{gpic} {\bf gpic -t}
with a printer driver that understands {\bf tpic} specials,
typically \cite{dvips} {\bf dvips}.  In some installations, {\bf gpic}
is simply named {\bf pic,} but make sure that GNU {\bf pic} \cite{gpic}
is being invoked rather than the older Unix {\bf pic.}
An alternative is \dpic, as described later in this document.
\Pic\ processors contain basic macro facilities,
so some of the concepts applied here require only a \pic\ processor.

With judicious use of macros the features of both \Mfour\ and 
\pic\ can be exploited.
The fastidious reader might observe that there are 3 languages being
scrambled: \Mfour, \pic, and the {\bf tpic,} {\bf tex} or
other output, not to mention the meta-language of the macros, and that
this mixture might be a problem, but experience implies otherwise.

\subsection{Quick start}
The contents of file {\tt quick.m4} are shown below to illustrate the
language, to show several ways for placing circuit elements, and to
give you enough information to produce basic labelled circuits such as
Figure \ref{quick}.
\begin{figure}[hbt]
   \input quick
   \caption{Diagram produced by file {\tt quick.m4}}
   \label{quick}
   \end{figure}

{\small \input quick.verb }

To process the file, make sure that the libraries {\bf libcct.m4} and
{\bf libgen.m4} are accessible.
%  Here it is assumed that they are in your {\tt lib} directory.
Verify that \Mfour\ is installed.
Now there are at least two possibilities, as follows, with slightly simpler
usage to be given in Section \ref{Simplified}.

\subsubsection{Processing with \gpic}
If you are using {\bf gpic} (on some systems the \gpic\ command is {\tt pic}),
do the following.  Type
\begin{verbatim}
  m4 <path>libcct.m4 quick.m4 > quick.pic
  gpic -t quick.pic > quick.tex
\end{verbatim}%\vspace{-2ex}
where {\tt <path>} is the path to the {\tt libcct.m4} file.

At the place in the \LaTeX\ source where the figure is to be included, put the
lines
\begin{verbatim}
\begin{figure}[hbt]
   \input quick
   \centerline{\box\graph}
   \caption{Customized caption for the figure}
   \label{Symbolic_label}
   \end{figure}
\end{verbatim}%\vspace{-2ex}
where the caption and label are customized for the figure.  Then \LaTeX\ the
document.

\subsubsection{Processing with \dpic}
If you are using {\bf dpic} with the PSTricks macros, the commands are
\begin{verbatim}
  m4 <path>pstricks.m4 <path>lib/libcct.m4 quick.m4 > quick.pic
  dpic -p quick.pic > quick.tex
\end{verbatim}%\vspace{-2ex}
and the document should have
the statement \verb|\usepackage{pstricks}| in the header.
The figure inclusion statements are
\begin{verbatim}
\begin{figure}[hbt]
   \centering
   \input quick
   \caption{Customized caption for the figure}
   \label{Symbolic_label}
\end{figure}
\end{verbatim}%\vspace{-2ex}

In both cases, the essential line is \verb|\input quick| which
inserts the previously-created file {\tt quick.tex}.

\subsubsection{Simplifications}\label{Simplified}
If appropriate
{\tt include()} statements are placed at the top of the file {\tt quick.m4},
then the \Mfour\ commands illustrated above can be shortened to

\verb|m4 quick.m4 > quick.pic|

\noindent
For example, the following two lines can be inserted before the
line containing {\tt .PS}:

{\tt include(<path>pstricks.m4)}\par
{\tt include(<path>libcct.m4)}

\noindent
where {\tt <path>} is the path to the folder containing the libraries.
Only the second line is necessary if \gpic\ is used or if the libraries
were installed so that PSTricks is assumed by default.
On some systems, setting the environment variable {\tt M4PATH} to
the library folder allows the above lines to be simplified to

{\tt include(pstricks.m4)}\par
{\tt include(libcct.m4)}

In the absence of a need to examine the file {\tt quick.pic},
the commands for producing the {\tt .tex} file can be reduced to

\verb%m4 quick.m4 | dpic -p > quick.tex%

When many files are to be processed, then a facility such as Unix {\bf make},
which is also available in several PC versions, can be used to
automate the manual commands given above.  On systems without such a
facility, a scripting language can be used, or you can put several
diagrams into a single source file so that they get processed together.
Put each diagram in the body of a \LaTeX\ macro, as shown:

\newcommand{\NVL}{\\\hspace*{\parindent}}
\par
\verb|\newcommand{\diaA}{%|\NVL
\verb|.PS|\NVL
{\sl drawing commands}\NVL
\verb|.PE|\NVL
\verb|\box\graph }%  \box\graph not required for dpic|\NVL
\verb|\newcommand{\diaB}{%|\NVL
\verb|.PS|\NVL
{\sl drawing commands}\NVL
\verb|.PE|\NVL
\verb|\box\graph }%  \box\graph not required for dpic|\NVL
\noindent Process the file using \Mfour\ and \dpic\ or \gpic\ to produce
a {\tt.tex} file, insert this into the \LaTeX\ source using \verb|\input|, and 
invoke the macros at the appropriate places.
If you include more than one diagram in a source file, remember that
macro definitions are preserved between diagrams.

\section{\Pic\ essentials}

\Pic\ source is a sequence of lines in a file.  Each diagram usually
corresponds to a separate file, but this is not essential.
The first line of a diagram begins with {\tt .PS} with optional following
arguments, and the last line is normally {\tt .PE}.
Lines outside of these are passed through the \pic\ processor unchanged.

The visible objects can be divided conveniently into two classes, the
{\em linear} objects {\tt line, arrow, spline, arc,} and the
{\em planar} objects {\tt box, circle, ellipse.}

The object {\tt move} is linear but draws nothing.  A composite object,
or {\tt block,} is planar and is a set of simpler objects contained
within square brackets: {\tt [} {\sl objects} {\tt ]}.

Text strings, typically meant to be typeset by \LaTeX, have
the double quote character at the beginning and end.  Their typeset
dimensions are unknown in advance, but can be obtained as demonstrated
in Section \ref{Interaction:}.

\Pic\ allows the definition of real-valued variables, which are alphameric
names beginning with lower-case letters, and computations using them.

Finally, positions on the diagrams can be defined, either indpendently
or relative to drawn objects.  The name of a position begins with an
upper-case letter.

\subsection{Manuals}
At the time of writing, the classic \pic\ manual \cite{KRpic} can be obtained
from URL:

\verb|ftp://cm.bell-labs.com/cm/cs/cstr/116.ps.gz|

A more complete manual \cite{Raymond95} is included in the GNU {\bf groff}
package.  Compressed postscript versions of both are available from

\verb|http://ece.uwaterloo.ca/~aplevich/dpic/|

In both of the above, explicit use of {\bf *roff} string and font
constructs should be replaced by their \LaTeX\ equivalents as necessary.
Further explanation is available, for example, from the {\bf gpic}
`man' page, part of the GNU {\bf groff} package.

Examples of use of the circuit macros in an electronics
course are available on the web \cite{Clark99}.

For a discussion of
the use of ``little languages'' in document production, and of \pic\ %
in particular, see Chapter 9 of  \cite{Bentley88}.
Chapter 1 of  \cite{Goossens97} also contains a brief discussion of this
and other languages.
Section \ref{Interaction:} of this document describes how to overcome the
problem mentioned in  \cite{Goossens97} of determining the dimensions of
typeset text in diagrams.

\subsection{The linear objects: {\tt line, arrow, spline, arc}}
A line can be drawn as follows:

{\tt line from} {\sl position} {\tt to} {\sl position}

\noindent
where {\sl position} is defined below, or

{\tt line} {\sl direction} {\sl distance}

\noindent
where {\sl direction} is one of {\tt up,} {\tt down,} {\tt left,}
{\tt right.} When used with the \Mfour\ macros described here, it is
preferable to add an underscore: {\tt up\_,} {\tt down\_,} {\tt left\_,}
{\tt right\_.} The {\sl distance} is a number or expression,
and the units are inches, but the assignment

{\tt scale = 25.4}

\noindent
has the effect of changing the units to millimetres,
as described in Section \ref{scaling:}.

Lines can also be drawn to any distance in any direction.  The example,

{\tt line up\_ 3/sqrt(2) right\_ 3/sqrt(2)}

\noindent
draws a line 3 units long from the current location,
at a $45^\circ$ angle above horizontal.

The above methods of specifying the direction and length of a line
are referred to as a {\em linespec} in this document.

Lines can be concatenated.  For example to draw a triangle:

{\tt line up\_ sqrt(3) right\_ 1 then down\_ sqrt(3) right\_ 1 then left\_ 2}

A {\sl position} can be defined by a coordinate pair, e.g.\ {\tt 3,2.5},
more generally using parentheses by {\tt (}{\sl expression, expression}{\tt )},
or by the construction {\tt (}{\sl position, position}{\tt)},
the latter taking the $x$-coordinate from the first position and the
$y$-coordinate from the second.  A position can be given a symbolic
name beginning with an upper-case letter, e.g.\ {\tt Top:~(0.5,4.5)}.
Such a definition does not affect the calculated figure boundaries.
The current position {\tt Here} is always defined.
The coordinates of a position are accessible, e.g.\ {\tt Top.x} and {\tt Top.y}
can be used in expressions.
The center, start, and end of linear objects are valid positions, for example:

{\tt line from last line.start to 2nd last arrow.end then to 3rd line.center}

\noindent
which also illustrates how to refer to a previously-drawn element if
it has not been given a name.

Objects can be named (using a name commencing with an upper-case letter),
for example:

{\tt Bus23: line up right}

\noindent
after which positions associated with the object can be referenced using the
name, for example:

{\tt arc cw from Bus23.start to Bus23.end with .center at Bus23.center}

An arc is drawn by specifying its rotation, starting point, end point, and
center, but sensible defaults are assumed if any of these are omitted.

The linear objects can be given arrowheads at the start, end, or both ends,
for example:

{\tt line dashed <- right 0.5\hfill\break
\hspace*{\parindent}%
arc <-> height 0.06 width 0.03 ccw from Here to Here+(0.5,0)
 \char92\hfill\break
\hspace*{2\parindent}%
   with .center at Here+(0.25,0)\hfill\break
\hspace*{\parindent}%
spline -> right 0.5 then down 0.2 left 0.3 then right 0.4}

The arrowheads on the arc above have had their shape adjusted using the
{\tt height} and {\tt width} parameters.

Finally, lines can be specified as {\tt dotted,} {\tt dashed,} or
{\tt invisible,} as in the above example.

\subsection{The planar objects: {\tt box, circle, ellipse}}
The planar objects are drawn by specifying the width, height, and
position of the center, thus:

{\tt A: box ht 0.6 wid 0.8 at (1,1)}

\noindent
after which, in this example, the position {\tt A.center} is a defined
position, and can be written simply as {\tt A}.  In addition, the
compass corners {\tt A.n,} {\tt A.s,} {\tt A.e,} {\tt A.w,} {\tt A.ne,}
{\tt A.se,} {\tt A.sw,} {\tt A.nw,} are all defined, as are the dimensions
{\tt A.height} and {\tt A.width.}  For example, two touching circles can
be drawn as shown:

{\tt circle radius 0.2\hfill\break 
\hspace*{\parindent}%
circle diameter (last circle.width * 1.2) with .sw at last circle.ne}

The planar objects can be filled with gray by the {\tt fill} {\sl number}
parameter, where {\sl number}$=0$ means black, and {\sl number}$=1$ means
white.  Omitting the number produces a medium gray.  Thus, for example,

{\tt box dashed fill}

\noindent produces a gray dashed box.

Colours and more elaborate line and fill styles are not part of the
basic \pic\ language, but can be incorporated, depending on the printing
device, by inserting {\tt \char92 special} commands or other
lines beginning with a backslash in the drawing code.
In fact, arbitrary lines can be inserted into the output using

{\tt command "}{\sl string}{\tt "}

\noindent where {\sl string} is the line to be output.

\subsection{Compound objects}
A group of statements enclosed in square brackets can be placed as if it
were a box.
Thus, the code fragment shown is found in a large digital diagram:

{\tt Ands: [ right\_
                                    \hfill\break\hspace*{2\parindent}%
   And1: AND\_gate
                                    \hfill\break\hspace*{3\parindent}%
      line right\_ del/2 then down\_ del*3/2 \char92
                                    \hfill\break\hspace*{4\parindent}%
      then left\_ And1.Out.x-And1.In1.x+del then down\_ del then right\_ del/2
                                    \hfill\break\hspace*{2\parindent}%
   And2: AND\_gate with .In1 at Here
                                    \hfill\break\hspace*{3\parindent}%
      line from And2.Out right\_ del/2 then down\_ del then right\_ del/2
                                    \hfill\break\hspace*{2\parindent}%
   ...
   ] with .And2.In1 at (K.x+2*del,IC5.Pin9.y)
   }

In the above, each of the gate macros evaluates to a composite object
in which the positions {\tt Out}, {\tt In1}, and others are defined.  Several
gates and connecting lines are contained in a block that is placed such
that position {\tt In1} within {\tt And2} is at a predefined position.


\subsection{Other language elements}

All objects have default sizes, directions, and other characteristics,
so part of the specification of an object can sometimes be profitably
omitted.

Another possibility for defining positions is 

{\sl expression} {\tt of the way between} {\sl position}
 {\tt and} {\sl position}

\noindent%
which is abbreviated as

{\sl expression} {\tt <} {\sl position} {\tt ,} {\sl position} {\tt >}

\noindent%
but care has to be used in processing the latter construction with \Mfour,
since the comma may have to be put within quotes, {\tt `,'} to distinguish it
from the {\tt m4} argument separator.

Positions can be calculated using expressions containing variables.
The scope of a position is the current block.  Thus, for example,

{\tt
  theta = atan2(B.y-A.y,B.x-A.x)

  line to Here+(3*cos(theta),3*sin(theta)).
  }

Expressions are the usual algebraic combinations of primary quantities:
constants, environmental parameters such as {\tt scale,}
named variables,
horizontal or vertical coordinates, using the constructs {\sl position}{\tt.x}
or {\sl position}{\tt.y},
dimensions of \pic\ objects, e.g.\ {\tt last circle.rad}.

The logical operators {\tt ==, !=, <=, >=, >, <} apply to
expressions, and strings can be tested for equality or inequality.  A
modest selection of numerical functions is also provided: the
single-argument functions {\tt sin, cos, log, exp, sqrt, int}, where
{\tt log} and {\tt exp} are base-10, the binary functions {\tt
atan2, max, min,} and the random-number generator {\tt rand()}.

A \pic\ manual should be consulted for details and more examples, and for
other facilities, such as the branching facility,

{\tt if} {\sl expression} {\tt then \char123} {\sl anything} 
  {\tt\char125\ else \char123} {\sl anything} {\tt\char125},

\noindent%
the looping facility,

{\tt for} 
{\sl variable} {\tt =} {\sl expression} 
{\tt to} {\sl expression} 
{\tt by} {\sl expression} 
{\tt do \char123} {\sl anything} {\tt\char125}, 

\noindent%
operating-system commands, string handling, \pic\ macros, and file inclusion.
Local and global variables and elementary file facilities are available.

\section{Two-terminal elements}\label{Basictwo}
All fundamental two-terminal element macros have been constructed
according to the conventions described below.

First, all drawing macros have default arguments, so that only arguments
different from default need be specified.  The arguments are given
in Section\ \ref{defines}.

Consider the resistor shown in Fig.\ \ref{BigResistor+},
which also serves as an example of \pic\ commands.

\begin{figure}[hbt]
   \input BigResistor+
   \caption{Resistor (with label {\tt R1}), showing the enclosing block}
   \label{BigResistor+}
   \end{figure}

The first part of the source for Fig.\ \ref{BigResistor+} is as follows:
{\small \input BigResistor+1.verb }

\subsection{Circuit and element basics}
The lines of Fig.\ \ref{BigResistor+}
and the remaining source lines of the file are explained below:
\begin{itemize}
\item The first line invokes an almost-empty macro that initializes
   local variables used by some circuit-element macros.  This macro can
   be customized to set line thicknesses, maximum page sizes, scale
   parameters, or other global quantities as desired.
\item By default, the size of two-terminal elements is a multiple of the
   \pic\ variable {\tt linewid,} which has initial value $0.5\,$in., so
   the value $2.0$ is assigned to this variable to make a suitably big
   diagram for this manual.  The body size of an element is determined
   by the macro {\tt dimen\_}, which evaluates by default to {\tt linewid,}
   and the default element length is {\tt elen\_,} which is {\tt dimen\_*3/2}
   by default.  These dimensions can all be customized.  For resistors,
   the length of the body is {\tt dimen\_/2,} and the width is {\tt dimen\_/6.}
\item The macro {\tt linethick\_} sets the thickness of subsequent
   lines (to 2.0pt in the example).
\item The two-terminal element macros expand to sequences of drawing commands
   that begin with {\tt `line invis {\sl linespec}'},
   where {\tt\sl linespec} is the first argument of the macro if it
   is non-blank, otherwise by default the line is drawn a distance
   {\tt elen\_} in the current direction, which is to the right by
   default. The invisible line is first drawn, then the element is drawn
   on top of the line.
   The element---rather the initially-drawn invisible line---can
   be given a name, {\tt R1} in the example, so that positions
   {\tt R1.start} and {\tt R1.end} are defined as shown and {\tt R1.center}
   is also defined.
\item The element body is enclosed by a block, which later can be
   used to place labels around the element.  The block
   corresponds to an invisible rectangle with horizontal top and bottom lines,
   regardless of the direction in which the element is drawn.  In the diagram a
   dotted box has been drawn to show the block boundaries.
\item The last sub-element, identical to the first in each two-terminal
   element, is an invisible line that can be referenced later to
   place labels or other elements.  This may be over-kill.  If you create
   your own macros you might choose simplicity over generality, and only
   include visible lines.
  \end{itemize}

To produce Fig.\ \ref{BigResistor+}, the following embellishments were included
after the previously-shown source:
{\small \input BigResistor+2.verb }

\begin{itemize}
\item The line thickness is set to the default thin value of 0.4pt, and
   the box displaying the element body block is drawn.  Notice how the
   width and height can be specified, and the box centre positioned at
   the centre of the block.
\item The next paragraph draws two objects, a spline with an arrowhead,
   and a string left justified at the end of the spline.  Other
   string-positioning modifiers than {\tt ljust} are {\tt rjust,}
   {\tt above,} and {\tt below.} Lines to be read by \pic\ can be
   continued by putting a backslash as the rightmost character. 
%  Furthermore any position, such as
%  {\tt R1.c} in the example, has an $x$-coordinate and $y$-coordinate
%  usable in expressions as, for example, {\tt R1.c.x} and {\tt R1.c.y.}

\item The last paragraph invokes a macro for dimensioning diagrams.
   Lines can be broken before a macro argument because \Mfour\ ignores
   white space before arguments.
   \end{itemize}

\subsection{The two-terminal elements}
Figs.\ \ref{CctTable+} and \ref{AmpTable+} are tables of the two-terminal
elements.
Several elements are included more than once to illustrate some of their
arguments.  The arguments for each element are listed in
Section\ \ref{defines}.
\begin{figure}[hbt]
   \input CctTable+
   \caption{Two-terminal element macros, with some variations}
   \label{CctTable+}
   \end{figure}
\begin{figure}[hbt]
   \input AmpTable+
   \caption{Amplifier, delay, and integrator}
   \label{AmpTable+}
   \end{figure}
In the \Mfour\ language, macro arguments are included within parentheses
following the macro name, with no space between the name and the
opening parenthesis.

The first argument of the two-terminal elements, if included, defines
the line direction and length along which the element is drawn.  The other
arguments produce variants of the default elements.
Thus, for example,

{\tt resistor(up\_ 1.25,7)}

\noindent%
draws a resistor 1.25 units long up from the current position, with $7$
vertices per side.
The name {\tt up\_} is a macro that resets the current macro and
\pic\ directional parameters to point up.

Most of the two-terminal elements are oriented; they have a defined
polarity.  Several, such as {\tt battery} or {\tt diode}, have an
argument that reverses polarity, but there is also a more general mechanism.
The first argument of the macro

{\tt reversed(`}{\sl macro name}{\tt',}{\sl macro arguments}{\tt )}

\noindent
is the name of a two-terminal element in quotes, followed by the
element arguments.  The element is drawn with reversed direction.
Thus,

{\tt diode(right\_ 0.4); reversed(`diode',right\_ 0.4)}

\noindent
draws two diodes to the right, but the second one points left.

\subsection{Branch-current arrows}
The macro

   {\tt b\_current({\sl label,} above\_|below\_, In|Out, Start|End)}

\noindent
draws an arrow from the start of the last-drawn two-terminal element
toward the body.  If the fourth argument is {\tt End}, the arrow is
drawn from the end of the element toward the body.  If the third
element is {\tt Out}, the arrow is drawn out, away from the body.
\begin{figure}[hbt]
   \input currents+
   \caption{Illustrating {\tt b\_current}}
   \label{currents+}
   \end{figure}
The first argument is an optional label, of which the default position is
the macro {\tt above\_,} which evaluates to {\tt above} if the current
direction is right, or to {\tt ljust, below, rjust} if the current direction
is respectively down, left, up.  A non-blank second argument specifies
the relative position, for example {\tt below\_,} which places the
label below with respect to the current direction, or an absolute
position, for example {\tt below,} or {\tt ljust,} with respect to the
arrowhead.

\subsection{Labels}
   Macros for labelling two-terminal elements are included:
\par
{\tt
   llabel(} {\sl arg1,arg2,arg3} {\tt )
      \hfill\break\hspace*{\parindent}%
   clabel(} {\sl arg1,arg2,arg3} {\tt )
      \hfill\break\hspace*{\parindent}%
   rlabel(} {\sl arg1,arg2,arg3} {\tt )
      \hfill\break\hspace*{\parindent}%
   dlabel(} {\sl long,lat,arg1,arg2,arg3} {\tt )
   }

The first macro places the three arguments, which are treated as math-mode
strings, on the left side of the element block {\em with respect to the
current direction:} {\tt up, down, left, right.}
The second places the arguments along the centre, and the third along the
right side.
Thus a simple circuit example with labels is
{\small \input Loop+.verb }
\begin{figure}[hbt]
   \input Loop+
   \caption{A loop with labelled elements}
   \label{Loop+}
   \end{figure}
\noindent which produces Fig.\ \ref{Loop+}.
The macro {\tt dlabel} performs the above functions for an
obliquely-drawn element, placing the three macro arguments at
{\tt vec\_(-long,lat),} {\tt vec\_(0,lat),} and {\tt vec\_(long,lat)}
respectively relative to the centre of the element.  Labels beginning
with a double quote are copied literally rather than assumed to be in
math mode.

\section{Other circuit elements}
Many basic elements are not two-terminal.  Fig.\ \ref{Misc+} shows
an operational amplifier, variants of the transformer macro,
and some ground symbols.
The ground symbol macro has three arguments:

{\tt ground( at }{\sl position}{\tt, T, N|F|S|L|P )}
\begin{figure}[hbt]
   \input Misc+
   \caption{Miscellaneous basic elements}
   \label{Misc+}
   \end{figure}

\noindent
so that, for example, the lines {\tt

move to (1.5,2); ground

ground(at (1.5,2)) }

\noindent have identical effect.  The second argument truncates
the stem, and the third defines the symbol type.

The opamp, transformer, and most other non-two-terminal elements are
enclosed in a block, and therefore may be named.  They generally
contain named locations in the interior.  An invisible line determining
length and direction (but not position) can be specified by the first argument,
as for the two-terminal elements.  Instead of positioning by the first
line, the enclosing block must be placed as shown:
  {\sl element}{\tt (}{\tt at} {\sl position}{\tt ),}
or by using its compass corners, thus:
  {\sl element} {\tt with} {\sl corner} {\tt at} {\sl position,} 
or, when the block contains a predefined location, thus:
  {\sl element} {\tt with} {\sl location} {\tt at} {\sl position.}

The operational amplifier, with macro

{\tt opamp( }{\sl linespec, -, +}{\tt )}

\noindent is enclosed in a block
containing the three predefined internal locations shown on the diagram,
{\sl In1,} {\sl In2,} and {\sl Out}, which can be referenced in later
commands, for example as `{\tt last [].Out}.'
The first argument defines the direction and length of the opamp, but the
position is determined either by predefined enclosing block of the opamp,
or by a construction such as `{\tt opamp with .In1 at Here}' which places
the internal position {\sl In1} at the specified location.
There are optional second and third arguments for which the defaults
are {\tt\$-\$} and {\tt \$+\$} respectively.  For example, the following
code fragment places an opamp with three connections as shown:

\noindent\parbox{4in}{\small \input oax.verb }%
\quad\raise-.3in\hbox{\input oax+ }

The transformer macro is

{\tt transformer( }{\sl linespec, }{\tt L|R, np, A, ns )}

\noindent and has predefined internal locations
{\sl P1,} {\sl P2,} {\sl S1,} and {\sl S2.}  The first argument
specifies the direction and distance from {\sl P1} to {\sl P2}, with
position determined by the enclosing block as for opamps.  The second
argument places the secondary side of the transformer to the left
or right of the drawing direction.  The optional third argument specifies
the number of primary arcs, the fourth omits the iron core, and the fifth
specifies the number of secondary arcs.
A transformer with four connections is illustrated as follows:

\noindent\parbox{4in}{\small \input tran.verb }%
\quad\raise-.3in\hbox{\input tran+ }

Fig.\ \ref{Nport+} illustrates the seven-argument {\tt nport} macro.
\begin{figure}[hbt]
   \input Nport+
   \caption{The {\tt nport} macro draws a sequence of pairs of named pins
     on each side of a box.  The default is a twoport.  The pin names are
     shown.}
   \label{Nport+}
   \end{figure}
The first argument is a box specification, such as
size or fill parameters, or text.  The second
to fifth arguments specify the number of ports (pin-pairs)
to be drawn respectively
on the west, north, east, and south sides of the box.  The end of each pin has
a name corresponding to the side, port number and $a$ or $b$ pin, as
shown.  The sixth argument specifies the ratio of port width
to inter-port space, and the last argument is the pin length.  The complete
structure is enclosed in a block. 

Fig.\ \ref{Relay+} shows some variants of the macro

{\tt contact(O|C, R)}
\hfill\break\noindent which contains predefined locations {\sl P, C, O}
for the armature and normally closed and normally open terminals.
The macro

{\tt relay(}{\sl poles}{\tt, O|C, R)}
\hfill\break\noindent defines coil terminals {\sl V1, V2} and contact
terminals {\sl P$_i$, C$_i$, O$_i$.} 
\begin{figure}[hbt]
   \input Relay+
   \vspace{-1ex}
   \caption{Variants of the {\tt contact} and {\tt relay} macros
   (default direction right)}
   \label{Relay+}
   \end{figure}
\begin{figure}[hbt]
   \input Bip+
   \vspace{-1ex}
   \caption{Bipolar transistor variants (current direction upward)}
   \label{Bip+}
   \end{figure}

Fig.\ \ref{Bip+} shows the variants of bipolar transistor macro

{\tt bi\_tr( }{\sl linespec, }{\tt L|R, P, E)}

\noindent which contains predefined internal locations {\sl E},
{\sl B}, {\sl C}.  The first argument defines the distance and direction
from {\sl E} to {\sl C,} with location determined by the enclosing
block as for other elements, and the base placed to the left or right of the
current drawing direction according to the second argument.  Setting the third
argument to `{\tt P}' creates a PNP device instead of NPN, and setting the
fourth to `{\tt E}' draws an envelope around the device.  Thus for example, the
following code fragment places a bipolar transistor and connects a ground to
the emitter and a resistor to the collector as shown:

\noindent\parbox{4in}{\small \input bitr.verb }%
\quad\raise-.3in\hbox{\input bitr+ }

Some FETs with predefined internal locations {\sl S,} {\sl D,} and {\sl G} are
also included, with similar arguments to those of {\tt bi\_tr,} as shown in
Fig.\ \ref{fet+}.
\begin{figure}[hbt]
   \input fet+
   \caption{JFET, insulated-gate enhancement and depletion MOSFETS,
     and simplified versions of the MOSFETS, see  \cite{Sedra97}.
     These macros are wrappers that invoke the {\tt mosfet} and {\tt smosfet}
     macros.}
   \label{fet+}
   \end{figure}
The macros in the figure are wrappers for the general {\tt smosfet}
and {\tt mosfet} macros.  The latter has an option for a disconnected
substrate, illustrated in Fig.\ \ref{mosfet+}.
\begin{figure}[hbt]
   \input mosfet+
   \caption{The macro {\tt mosfet(}{\sl linespec}{\tt,L|R,P,[D][B],E)}
     has a disconnected-substrate option.}
   \label{mosfet+}
   \end{figure}
Similarly a UJT macro with predefined internal locations {\sl B1,} {\sl B2,}
and {\sl E} is illustrated in Fig.\ \ref{ujt+},
\begin{figure}[hbt]
   \input ujt+
   \caption{UJT variants, with current drawing direction up. }
   \label{ujt+}
   \end{figure}
and an SCR macro with predefined internal locations {\sl T1,} {\sl T2,}
and {\sl G} is illustrated in Fig.\ \ref{scr+}.
The number of possible semiconductor symbols is very
large, so these macros must be regarded as prototypes.
Some other non-two-terminal macros are {\tt dot} which has an
optional argument `{\tt at} {\sl location}', the line-thickness
macros, the {\tt fill\_} macro, and {\tt crossover,} which is a useful if
archaic method to show non-touching conductor crossovers, as in
Figure \ref{ex10+}.
\begin{figure}[h!t]
   \input scr+
   \caption{SCR variants, drawing direction to the right. }
   \label{scr+}
   \end{figure}
\begin{figure}[h!b]
   \input ex10+
   \vspace{-1ex}
   \caption{Bipolar transistor circuit, illustrating {\tt crossover}}
   \label{ex10+}
   \end{figure}
%\clearpage

\section{Directions}
Aside from its block-structure capabilities, looping, and macros, 
\pic\ has a very useful concept of the current point and current direction,
the latter unfortunately limited to {\tt up, down, left, right.}  Objects can
be drawn at absolute locations or placed relative to previously-drawn
objects.  These macros need to know the current direction so
whenever {\tt up, down, left, right} are used they should be written as
{\tt up\_, down\_, left\_, right\_} which are macros.

To draw circuit objects in other than the standard four directions,
the macros {\tt Point\_(}{\sl degrees}{\tt ),} {\tt point\_(}{\sl
radians}{\tt ),} and {\tt rpoint\_(}{\sl rel linespec}{\tt )} re-define the
direction-cosine macros {\tt x\_, y\_} which are used within
element-drawing macros.  Thus `{\tt Point\_(-30); resistor}' draws a
resistor along a line with slope -30 degrees. `{\tt rpoint\_(to Z)}'
sets the current direction cosines to point to location Z.
Macro {\tt vec\_(x,y)} evaluates
to the position {\tt (x,y)} rotated by the argument of the previous
{\tt Point\_, point\_} or {\tt rpoint\_} command.  The macro {\tt
rvec\_(x,y)} evaluates to position {\tt Here + vec\_(x,y)} and is the
principal device used to define relative locations in the circuit
macros.  Thus, {\tt line to rvec\_(x,0)} draws a line of length
{\tt x} in the current direction.
%  For convenience, macros
%{\tt rline} and {\tt rmove} draw and move respectively from the current
%position in the current direction, so that, e.g.\ {\tt rmove(x)} moves
%distance {\tt x} in the current direction.

Fig.\ \ref{Oblique+} shows a circuit drawn using the above
macros.  The source for the figure is below, and illustrates that some
hand-placement of labels using {\tt dlabel} may be useful when elements
are drawn other than horizontal or vertically.
\begin{figure}[hbt]
   \input Oblique+
   \vspace{-2ex}
   \caption{Illustrating elements drawn at oblique angles}
   \label{Oblique+}
   \end{figure}
{\small \input Oblique+.verb }
Since \Mfour\ macro arguments
are separated by commas, any commas that are integral parts of the
arguments must be protected either by parentheses as illustrated in
{\tt inductor(from Cr to Cr+vec\_(elen\_,0))},
or by multiple single quotes, {\tt `{}`,'{}',} as necessary.
Commas also may be avoided by writing
{\tt 0.5 between L and T} instead of {\tt 0.5<L,T>.} 

\section{Logic gates}
\begin{figure}[hbt]
   \input NOR+
   \caption{Illustrating {\tt NOR\_gate(3)}}
   \label{NOR+}
   \end{figure}
Fig.\ \ref{NOR+} shows a 3-input NOR gate, with the enclosing block
and predefined internal locations {\tt Out,} {\tt In1}--{\tt In3}.
Gate macros have an optional argument, an integer from
$0$ to $N$ where $N$ can be up to approximately 5, defining locations
{\tt In1,} $\cdots$ {\tt In}$N.$  By default $N=2,$
except for macros {\tt NOT\_gate} and {\tt BUFFER\_gate} which
have one input {\tt In1}, unless they are given an argument, which
is treated as the line specification of a two-terminal element.
\begin{figure}[hbt]
   \input Liblog+
   \caption{Basic logic gate library}
   \label{Liblog+}
   \end{figure}
Fig.\ \ref{Liblog+} shows these and the other basic logic gates included in
library {\tt liblog.m4}.
These gates are typically not two-terminal elements and are normally
drawn horizontally or vertically (although arbitrary
directions may be set with e.g.\ {\tt Point\_({\sl degrees})}).
Each gate is contained in
a block of typical height {\tt 6*L\_unit} where {\tt L\_unit}
is a macro intended to establish line separation for an imaginary grid
on which the elements are superimposed.

The following
source produces the $SR$ flip-flop shown in Fig.\ \ref{FF+} to illustrate
change of direction.  Note that
when a gate is rotated, its input locations retain their positions
relative to the gate body.
{\small \input FF+.verb }
\begin{figure}[hbt]
   \input FF+
   \caption{$SR$ flip-flop}
   \label{FF+}
   \end{figure}

A good strategy for drawing complex logic circuits might be summarized
as follows:
\begin{itemize}
\item Establish the absolute locations of gates and other major components
  (e.g.\ chips) relative to a grid of mesh size commensurate with
  {\tt L\_unit}, which is an absolute length.
\item Draw minor components or blocks relative to the major ones, using
   parametrized relative distances.
\item Draw connecting lines relative to the components and previously-drawn
   lines.
\item Write macros for repeated objects.
\item Tune the diagram by making absolute locations relative, and by tuning
   the parameters.
   Some useful macros for this are the following, which are in units of
  {\tt L\_unit}:
   \begin{itemize}
   \item[] {\tt AND\_ht, AND\_wd}: the height and width of basic AND and
     OR gates
   \item[] {\tt BUF\_ht, BUF\_wd}: the height and width of basic buffers
   \item[] {\tt N\_diam}: the diameter of NOT circles
   \end{itemize}
   \end{itemize}
A useful exercise might be to reproduce the example of Fig.\ \ref{exVIII}.
\begin{figure}[hbt]
   \input ex08
   \caption{Multifunction latch circuit}
   \label{exVIII}
   \end{figure}

In addition to the basic logic gates described here, some experimental
flip-flop and IC chip diagrams are in the distributed example files.

\section{Element and diagram scaling}\label{scaling:}

There are several issues related to scale changes.  You may wish to use
millimetres, for example, instead of the default inches.  You may wish
to change the size of a complete diagram while keeping the relative
proportions of objects within it.  You may wish to change the sizes or
proportions of individual elements within a diagram.  You must take
into account that line widths are scaled separately from drawn objects,
and that the size of typeset text is independent of the \pic\ language.

The \pic\ scaling facilities will be described first, then
the scaling of the defined circuit elements.

\subsection{Pic scaling}
There are at least three kinds of graphical elements to be considered:
\begin{enumerate}
\item The default sizes of linear and planar \pic\ objects
  can be redefined by assigning values to the built-in \pic\ variables
  {\tt arcrad,} {\tt arrowht,} {\tt arrowwid,} {\tt boxht,} {\tt boxrad,}
  {\tt boxwid,} {\tt circlerad,} {\tt dashwid,} {\tt ellipseht,}
  {\tt ellipsewid,} {\tt lineht,} {\tt linewid,} {\tt moveht,} {\tt movewid,}
  {\tt textht,} {\tt textwid.}
  The $\cdots${\tt ht} and $\cdots${\tt wid} parameters refer to the
  default sizes of vertical and horizontal lines, moves, etc., except for
  {\tt arrowht} and {\tt arrowwid} which refer to arrowhead dimensions.
  The {\tt boxrad} parameter can be used to put rounded corners on boxes.

  Assigning a value to the variable {\tt scale} multiplies all the 
  built-in \pic\ dimension variables except {\tt arrowht,} {\tt arrowwid,}
  {\tt textht,} and {\tt textwid}
  by the new value of {\tt scale} (\gpic\ multiplies them all). 
  Thus the file {\tt quick.m4} can be modified to use millimetres as follows:
  
  \begin{verbatim}
  .PS                            # Pic input begins with .PS
  scale = 25.4                   # mm
  cct_init                       # Set defaults

  elen = 19                      # Variables can be used
  ...
  \end{verbatim}

  The {\tt .PS} line can be used to scale the entire drawing, regardless
  of its interior.  Thus, for example, the line {\tt.PS 100/25.4}
  scales the entire drawing to a width of 100$\,$mm.

  If the final picture width exceeds the value of {\tt maxpswid,} which
  has a default size of 8.5, then the picture is scaled to this value.
  Similarly if the height exceeds {\tt maxpsht,} (default 11), then the
  picture is scaled to fit.

\item The finished size of typeset text is independent of \pic\ variables,
  but can be determined as in Section \ref{Interaction:}.  Thus,
  once dimensions $x$ and $y$ are known, then {\tt "text" wid $x$ ht $y$}
  assigns the dimensions of {\tt text.}

\item Line widths are independent of diagram and text scaling, and have
  to be set independently.  For example,
  the assignment {\tt linethick = 1.2} sets the default line width to 1.2pt.
  The macro {\tt linethick\_({\sl points})} is also provided, together
  with default macros {\tt thicklines\_} and {\tt thinlines\_}.
% The unscaled environment parameters and their
% defaults are shown in the table below: 

% \begin{tabbing}
% \hskip 1.25in\= \hskip0.75in\= \hskip1.25in\=\\
% {\tt scale} \> {\tt 1.0} \>{\tt arrowhead} \> {\tt 1.0} \\
% {\tt linethick} \> {\tt -1.0} \>{\tt maxpswid} \> {\tt 8.5 } \\
% {\tt fillval} \> {\tt .5} \>{\tt maxpsht} \> {\tt 11.0} \\
% \end{tabbing}

% The {\tt linethick} variable specifies current line thickness in points.

\end{enumerate}

\subsection{Circuit scaling}
The circuit elements all have default dimensions
which are multiples of the \pic\ environmental parameter {\tt linewid,}
so changing this parameter changes default element dimensions.
The scope of a \pic\ variable is the current block; therefore a sequence
such as

{\tt
  resistor

  [ linewid = linewid*1.5; resistor ]

  resistor
}

\noindent%
produces a string of three resistors, the middle one larger than the other
two.
Alternatively, you may redefine the default length {\tt elen\_}
or the body-size parameter {\tt dimen\_.}  For example, adding the line

{\tt define(`dimen\_',dimen\_*1.2)}

\noindent%
after the {\tt cct\_init} line of {\tt quick.m4} produces slightly
larger element body sizes.

\section{Writing macros}\label{Writing:}
Writing basic macros in the \Mfour\ language is quite simple, and is
described in numerous documents such as the original
reference \cite{KRm4}, or in later manuals \cite{Seindal94}.  If a new
element is required, then modifying and renaming one of
the library definitions or simply adding an option to it may
suffice.  Hints for drawing general two-terminal elements are given in
{\tt libcct.m4}.  However if an element or composite is to be drawn in
only one orientation then most of the elaborations used for general
two-terminal elements in Section \ref{Basictwo} can be dropped.

A macro is defined using quoted name and replacement text, as follows:

{\tt define(`}{\sl name}{\tt',`}{\sl replacement text}{\tt ')}

After this line is read by the \Mfour\ processor, then whenever {\sl name}
is encountered as a separate string, it is replaced by its replacement
text, which may have multiple lines.  The quotation characters are used
to defer macro expansion.  Macro arguments are referenced inside a
macro by number; thus {\tt \$1} refers to the first argument.

In the following example,
two macros are defined to simplify the repeated drawing
of a series resistor and series inductor, and the macro {\tt tsection} defines
a subcircuit that is replicated several times to generate Figure \ref{Tline}.
{\small \input tline.verb }
\begin{figure}[hbt]
   \input tline
   \caption{A lumped model of a transmission line, illustrating the
    use of custom macros.}
   \label{Tline}
   \end{figure}

\section{Interaction with \LaTeX}\label{Interaction:}
By using a bit of hackery, the dimensions of typeset text can be
obtained and included in calculations within the diagram that contains
the text.  The difficulty is that font metrics are not known until
\LaTeX\ is invoked, and the solution is to process the diagram twice,
just as symbolic references in source text require files to be
processed twice.  First the diagram \verb|.m4| source is processed by
\Mfour\ and a \pic\ processor to make a \verb|.tex| file, and the
document source is \LaTeX{}ed to include the diagram and to write the
required text dimensions into a supplementary file.  Then the diagram
\verb|.m4| source and \LaTeX\ document source are processed again.

The file \verb|boxdims.sty| distributed with this package should be installed
where \LaTeX\ can find it, and should be invoked by
\verb|\usepackage{boxdims}| in the document source.
The essential idea in \verb|boxdims.sty| is to define a two-argument macro
\verb|\boxdims| which writes out definitions for the width, height and
depth of its typeset second argument into file {\sl jobname.}\verb|dim|,
where {\sl jobname} is the name of the main source file.
The first argument of \verb|\boxdims| is used to construct unique symbolic
names for these dimensions. 
Thus, the line

{\tt box \verb|"\boxdims{Q}{\Huge Hi there!}"| }

\noindent has the same effect as

{\tt box \verb|"\Huge Hi there!"|}

\noindent except that the line

{\tt define(`Q\_w',77.6077pt\_\_)define(`Q\_h',17.27779pt\_\_)%
define(`Q\_d',0.0pt\_\_)dnl}

\noindent is written into file {\sl jobname.}\verb|dim|
(and the numerical values depend on the current font).

The following small file, for example, produces the box shown in
Figure \ref{boxdims}:
{\small \input eboxdims.verb }
\begin{figure}[hbt]
   \input eboxdims
   \caption{Fitting a box to typeset text.}
   \label{boxdims}
   \end{figure}

First the source file for the figure
is processed by \Mfour\ and a \pic\ interpreter to produce a \verb|.tex| file,
then \LaTeX\ is run, and then these steps are repeated.
In {\bf m4,} \verb|sinclude(|{\sl jobname}\verb|.dim)| will
read the named file if it exists.
The macro \verb|boxdim(|{\sl name,suffix,default}\verb|)|
from {\bf libgen.m4} expands the expression \verb|boxdim(Q,w)|,
for example, to the value of \verb|Q_w| if it is defined, else to its
third argument if defined, else to 0, the latter two cases applying if
{\sl jobname.}\verb|dim| doesn't exist yet.  The values of
\verb|boxdim(Q,h)| and \verb|boxdim(Q,d)| are similarly defined, and
for convenience, \verb|boxdim(Q,v)| evaluates to the sum of these.
Macro \verb|pt__| is defined as \verb|*scale/72.27| in {\bf libgen.m4},
to convert points to drawing coordinates.

In rare cases, the size of the diagram will affect page breaks, requiring
the document source to be \LaTeX{}ed more than twice.  To avoid this
problem, the third argument of \verb|boxdim| can be used to define an
approximate initial size.

Another use of the \verb|\boxdims| macro is in calculating the global
dimensions of a diagram.  Consider the following example:

\begin{verbatim}
.PS
B: box
  "Left text" at B.w rjust
  "Right text: $x^2$" at B.e ljust
.PE
\end{verbatim}

The \pic\ interpreter cannot know the dimensions of the text to the left
and right of the box, and the resulting diagram is generated using
the dimensions of the box alone.  Modifying this example to

\vspace{1ex}
{\tt
\noindent .PS\hfill\break
sinclude({\sl jobname}.dim)\hfill\break
B: box\hfill\break
\verb|  "\boxdims{L}{Left text}" wid boxdim(L,w) ht boxdim(L,v) at B.w rjust|%
\hfill\break
\verb|  "\boxdims{R}{Right text: $x^2$}" wid boxdim(R,w) ht boxdim(R,v) at B.e ljust|%
\hfill\break
.PE}
\vspace{1ex}

\noindent assigns the correct width and height to the text strings,
and the picture dimensions are then calculated correctly.
The macros {\tt s\_init(}{\sl name}{\tt)} and
{\tt s\_box(}{\sl text},{\sl expr},$\cdots${\tt)}
are included to simplify the above example, as shown:

\vspace{1ex}
{\tt
\noindent .PS\hfill\break
sinclude({\sl jobname}.dim)\hfill\break
s\_init({\sl unique name})\hfill\break
B: box\hfill\break
\verb|  s_box(`Left text') at B.w rjust|\hfill\break
\verb|  s_box(`Right text: $x^%g$',2) at B.e ljust|\hfill\break
.PE}
\vspace{1ex}

The argument of {\tt s\_init} should be unique within {\tt{\sl jobname}.dim.}
It is used to generate a unique \verb|\boxdims| first argument for each
invocation of \verb|s_box| in the current file.
If there are two or more arguments to {\tt s\_box} as in the second
invocation of this macro above, then they are
passed to the {\tt sprintf()} function.
If \verb|s_init| has been omitted, the symbols ``{\bf !!}"
are inserted into the text as a warning.
Be sure to quote any commas in the arguments.  Since the first
argument is \LaTeX, make a rule of quoting it to avoid comma and name-clash
problems.

Further tricks can be played.  The example

\verb|S: s_box(`\includegraphics{|{\it file}\verb|.eps}') with .sw at 0,0|

\noindent shows a nice way of including eps graphics in a diagram.  When
processed twice, the included
picuture---defined by the string S in the example---has known position and
dimensions, which can be used add vector graphics or text to the picture.
To aid in overlaying planar objects,
the macro {\tt boxcoord(}{\sl planar object, x-fraction, y-fraction}{\tt)}
evaluates to a position, with {\tt boxcoord(}{\sl planar object}{\tt,0,0)}
at the lower left corner of the object, and
{\tt boxcoord(}{\sl planar object}{\tt,1,1)} at its upper right.

\section{{\bf PSTricks} tricks}
This section applies only to a \pic\ processor ({\bf dpic}) that is
capable of producing PSTricks output.
Arbitrary PSTricks commands can be mixed with \Mfour\ input to create
complicated effects, but some commonly required effects are particularly simple.

The rotation of text is illustrated by the file

{\small \input Axes.verb }

\noindent%
which produces horizontal text, and text rotated $90^\circ$ along the
vertical line.

Another common requirement is the filling of arbitrary shapes, as
illustrated by the following lines within a {\bf .m4} file:

\vspace{\parsep}
\noindent%
\verb|command "`\pscustom[fillstyle=solid,fillcolor=lightgray]{'"|
\hfill\break
{\sl drawing commands for an arbitrary closed curve}
\hfill\break
\verb|command "`}%'"|
\vspace{\parsep}

The macro {\tt shade(}{\sl gray value},{\sl closed line specs}{\tt )}
can be invoked to accomplish the same effect as the above example.

For colour printing or viewing, arbitrary
colours can be chosen, as described in the {\bf PSTricks} manual.
{\bf PSTricks} parameters can be set by inserting the line

\vspace{\parsep}
\noindent\verb|command "`\psset{|{\sl option = value,}$\;\cdots$\verb|}'"|
\vspace{\parsep}

\noindent%
in the drawing commands, or by using the macro
{\tt psset\_(}{\sl PSTricks options}{\tt )}.

\section{Developer's notes}
Several years ago in the course of writing a book I took a few days off
to write a \pic-like interpreter {\bf (dpic)} to automate the tedious
coordinate calculations required by latex picture objects.
The macros in this distribution and the interpreter are the result of that
effort and of drawings I have had to produce since.
The interpreter has been upgraded more recently to generate {\bf mfpic},
{\bf MetaPost} \cite{metapost}, {\bf Postscript}, and {\bf PSTricks} commands,
the latter my preference because of its quality and flexibility, including
facilities for colour and rotations, together with simple font selection.
In addition, {\bf xfig}-compatible output has been added.  Instead of
\pic\ macros I preferred the equally simple but more powerful \Mfour\ macro
processor, and therefore \Mfour\ is required here, although {\bf dpic} now
supports \pic-like macros.  Free versions of \Mfour\ are available for
Unix, Windows, and other operating systems.

If starting over today would I not just use one of the other drawing packages
available these days? The answer is that \pic\ is a good choice for the
moderate geometrical calculations that are sometimes necessary in line
drawings.  The language is simple to learn, and more importantly to read,
especially for backslash-phobics like me.  The language has built-in looping
and block-structure constructs that combine power with simplicity, and it has
stood the test of time.  However, no choice of tool is without compromise, and
making good graphics is time-consuming no matter how it is done.

Using the {\bf mfpic} output of {\bf dpic} it is possible to produce Metafont
alphabets of circuit elements or their subcomponents, thereby essentially
removing dependence on device drivers, but with the complication of treating
every graphic subcomponent as a \TeX\ box.  The {\bf xfig} output allows
elements to be defined and fine-tuned, and then using the interactive graphics
of {\bf xfig} to be quickly assembled into a circuit.  Further refinement of
the elements might still be required.  {\bf Dpic} will also issue low-level
{\bf MetaPost} or {\bf Postscript} commands, so that diagrams defined using
\pic\ can be manipulated and combined with others.  The user is responsible for
ensuring that the correct fonts are provided.

\section{Bugs}\label{Bugs:}
The distributed macros are not written for maximum robustness.  Macro
arguments could be tested for correctness and explanatory error
messages could be written as necessary, but that would make the macros
more difficult to read and to write.  You will have to read them when
unexpected results are obtained or when you wish to modify them.

Here are some hints, gleaned from experience and from comments I have
received.
\begin{enumerate}
\item 
{\bf Initialization:}
If the first element macro evaluated is non-two-terminal or is within a
\Pic\ block, then later macros evaluated outside the block may produce
the error message

{\tt there is no variable `rp\_ang'}

\noindent because {\tt rp\_ang} is not defined in the outermost scope of the
diagram.  To cure this problem, put the line

{\tt cct\_init}

\noindent immediately after the .PS line, or prior to the first block.  It is
entirely permissible to modify {\tt cct\_init} to include commonly-used
diagram initializations, such as the {\tt thicklines\_} statement, and
to invoke {\tt cct\_init} at the beginning of every diagram.
For completeness, macros {\tt gen\_init,} {\tt log\_init,} {\tt darrow\_init}
are also provided for cases where the circuit library is not needed.

\item 
{\bf Pic objects versus macros:}  A common error is to write something like

{\tt line from A to B; resistor from B to C}

\noindent when it should be

{\tt line from A to B; resistor(from B to C)}

\noindent This error is caused by an unfortunate inconsistency between the
linear \pic\ objects and the way {\bf m4} passes macro arguments.

\item 
{\bf Commas:}
Remember that macro arguments are separated by commas, and commas that are
part of an argument must be protected by parentheses or quotes.  Thus,

{\tt shadebox(box with .n at w,h)}

\noindent produces an error, whereas

{\tt shadebox(box with .n at w`,'h)}

\noindent and

{\tt shadebox(box with .n at (w,h))}

\noindent do not.

\item 
{\bf Quotes:} Single quote characters are stripped in pairs by \Mfour,
so the string

{\tt "`{}`inverse'{}'"}

\noindent will be typeset as if it were

{\tt "`inverse'".}

\noindent The cure is to add single quotes.

%\item {\bf Quoted strings in macros:}
  The most subtle part of writing
  \Mfour\ macros is deciding when to quote arguments.  In the context
  of circuits it seemed best to assume that macro arguments would not
  be protected by quotes at the level of macro invocation, but should
  be quoted inside each macro.  There may be cases where this rule is
  not optimal.

\item 
{\bf Dollar signs:}
The $i$-th argument of an \Mfour\ macro is {\tt \$}$i,$ where $i$ is
an integer, so the following construction can cause an error when it
is part of a macro,

{\tt "\$0\$" rjust below}

\noindent since {\tt \$0} expands to the name of the macro itself.
To avoid this problem, put the string in quotes, or write {\tt "\$`'0\$".}

\item 
{\bf Name conflicts:}  Using the name of a macro as part of
a comment or string is a simple and common error.
Thus,

{\tt arrow right \verb|"$\dot x$"| above}

\noindent produces an error message because {\tt dot} is a macro
name.   Macro expansion can be avoided by adding quotes, as follows:

{\tt arrow right `\verb|"$\dot x$"|' above}

Library macros intended only for internal use have names that begin
with {\tt m4} to avoid name clashes, but in addition, a good rule is to
quote all \LaTeX\ in the diagram input.

%A good rule is to process diagrams in separate files, and to use the TeX
%\verb|\input| command to include the result.
If extensive use of strings
that conflict with macro names is required, then one possibility is
to replace the strings by macros to be expanded by \LaTeX\ , for example
the diagram

{\tt
.PS

   \hspace*{\parindent} box \verb|"\stringA"|

.PE
}

\noindent with the LaTeX macro

{\tt
  \verb|\newcommand{\stringA}{|%

   \verb|Circuit containing planar inductor and capacitor}|
}

\item 
{\bf Current direction:} Some macros, particularly those for labels, do
unexpected things if care is not taken to preset the current direction
using macros {\tt right\_,} {\tt left\_,} {\tt up\_,} {\tt down\_,}
or {\tt rpoint\_($\cdot$).}
Thus for two-terminal macros it is good practice to write, e.g.

{\tt resistor(up\_ from A to B); rlabel(,R\_1)}

\noindent%
rather than 

{\tt resistor(from A to B); rlabel(,R\_1),}

\noindent%
which produce different results if the last-defined drawing direction is not
{\tt up}.  It might be possible to change the label macros to avoid this problem
without sacrificing ease of use.

\item {\bf Pic error messages:} Some errors are detected only after scanning
  beyond the end of the line containing the error.  The semicolon
  is a logical line end, so putting a semicolon at the end of lines may
  assist in locating bugs. 

\item {\bf Incompatible processors:} If you switch between e.g. {\bf dpic}
  and {\bf gpic,} remember that the libraries are set up to use {\bf gpic} 
  by default, otherwise {\tt pstricks.m4} or {\tt mfpic.m4} have to be
  processed before the other libraries.  To redefine the default behaviour,
  change the {\tt include} statements near the top of the libraries.

\item {\bf Scaling:} \Pic\ and these macros provide several ways to scale
  diagrams and elements within them, but subtle unanticipated effects
  may appear.  The line {\tt.PS} $x$ provides a convenient way to force
  the finished diagram to width $x.$  However if \gpic\ is the
  \pic\ processor then all scaled parameters are affected, including those
  for arrowheads and text, which may not be the desired
  result.  A good general rule is to use the {\tt scale} parameter for
  global scaling unless the primary objective is to specify overall
  dimensions.

\item {\bf Buffer overflow:} The \Mfour\ error message of the form
  \verb|pushed back more than 4096 chars| results from expanding large
  macros or macro arguments, and can be avoided by enlarging the buffer.
  For example, the option {\tt -B16000} enlarges the buffer size to 16000
  bytes.  However this error message could also result from a syntax
  error.

   \end{enumerate}

\section{List of macros}
\label{defines}
The following table lists the macros in libraries
darrow.m4, libcct.m4, liblog.m4, libgen.m4, and files gpic.m4, mfpic.m4,
and pstricks.m4.  Some of the example sources contain additional macros,
such as for flowcharts and binary trees.

Internal macros defined within the libraries begin with the characters
m4, and are not listed here.

The libraries define the \pic\ location {\tt M4\_Tmp} and following
\pic\ variables:

{\tt
m4azim
m4caz
m4cel
m4dll
m4dlw
m4elev
m4i
m4j
m4saz
m4sel
m4t1
m4t2
m4t3
m4tmp\hfill\break
rp\_ang
rp\_ht
rp\_len
rp\_wid%
.}

The library in which each macro is found is given, and a brief description.
\input defines
\endinput
