Index: /trunk/doc/misc/codeConventions.tex
===================================================================
--- /trunk/doc/misc/codeConventions.tex	(revision 128)
+++ /trunk/doc/misc/codeConventions.tex	(revision 128)
@@ -0,0 +1,1626 @@
+\documentclass[panstarrs]{panstarrs}
+\newcommand\note[1]{{\bf #1}}
+\newcommand\tbd[1]{{\bf [#1]}}
+
+\title{\PS{} Code Conventions}
+\author{Robert Lupton}
+\group{}
+\organization{}
+\docnumber{PSDC-???}
+
+\fancyhead{}
+\fancyhead[L]{\PS{} Document}
+\fancyhead[R]{PSDC-???}
+\fancyhead[C]{Revision 0.1 -- Draft}
+\fancyfoot[L]{\PS{} Coding Conventions}
+\fancyfoot[R]{\today}
+
+\begin{document}
+
+\newcommand{\matchBracket}[1]{}         % help emacs match properly
+\newcommand{\XXX}{{\color{red} XXX}}
+
+\pagenumbering{roman} \thispagestyle{empty} \maketitle
+
+\pagebreak \pagestyle{fancy}
+{ \Large \bf Revision History}
+\begin{center}
+\begin{tabular}{|p{1in}|p{1in}|p{4.5in}|}
+\hline
+{\bf Revision Number} & {\bf Release Date} & {\bf Description} \\
+\hline
+%0.1 & 2003/12/08 & First draft \\
+\hline
+\end{tabular}
+\end{center}
+
+{ \Large \bf Referenced Documents}
+\begin{center}
+\begin{tabular}{|p{1in}|p{2.75in}|p{2.75in}|}
+\hline
+{\bf \PS{} ID} & {\bf Title} & {\bf Author} \\
+\hline
+%%% References here.
+\hline
+\end{tabular}
+\end{center}
+
+\pagebreak
+\tableofcontents
+
+% \pagebreak
+% \listoffigures 
+\pagebreak \pagenumbering{arabic}
+
+\section{Introduction}
+
+\subsection{Why Have Code Conventions}
+
+Code conventions are important to programmers for a number of reasons:
+\begin{itemize}
+
+    \item 80\% of the lifetime cost of a piece of software goes to
+    maintenance.
+
+    \item Hardly any software is maintained for its whole life by
+    the original author.
+
+    \item Code conventions improve the readability of the software,
+    allowing engineers to understand new code more quickly and
+    thoroughly.
+
+    \item If you ship your source code as a product, you need to
+    make sure it is as well packaged and clean as any other
+    product you create.
+\end{itemize}
+
+
+\label{L16729} 
+\subsection{Acknowledgments}
+
+This document is derived from the Sun Microsystems Java language
+coding standards presented in the Java Language Specification
+(\code{http://java.sun.com/docs/books/jls/index.html}).
+
+\begin{verbatim}
+      Adapted with permission from
+      CODE CONVENTIONS FOR THE JAVA^TM PROGRAMMING LANGUAGE.
+      Copyright 1995-1999 Sun
+      Microsysytems, Inc.  All rights reserved.
+\end{verbatim}
+
+See the Java Code Conventions Web site
+(\code{http://java.sun.com/docs/codeconv/}) for more details.
+
+Such an adaption is is explicitly permitted by the Sun Microsystems
+copyright notice (Copyright.doc.html).
+
+\subsection{\label{L16730}To whom should I Complain?}
+
+While we're working on this document complain to
+\code{rhl@astro.princeton.edu}.
+
+
+%------------------------------------------------------------------------------
+
+\label{L16732} 
+\section{File Names}
+
+\emph{\XXX{} I don't discuss doxygen comments here.}
+
+This section lists commonly used file suffixes and names. 
+\label{L647} 
+\subsection{File Suffixes}
+
+
+
+Software uses the following file suffixes:
+\begin{center}
+\begin{tabular}{ll}
+\textbf{File Type} & \textbf{Suffix}\\
+C source & \code{.c} \\
+header files & \code{.h} \\
+SWIG interface files & \code{.i} \\
+\end{tabular}
+\end{center}
+
+\label{L253} 
+\subsection{Common File Names}
+
+Frequently used file names include: 
+\begin{center}
+\begin{tabular}{lp{3in}}
+\textbf{File Name} & \textbf{Use} \\
+\file{Makefile} &
+  The preferred name for makefiles.  We use \code{gnumake} to build our
+software.  \emph{Do we? \XXX{}} \\
+
+\file{README} & 
+The preferred name for the file that summarizes the contents of a
+particular directory. \\
+
+\code{TAGS} &
+The index file (built by etags) used by emacs to follow cross references. \\
+\end{tabular}
+\end{center}
+
+
+%------------------------------------------------------------------------------
+
+\label{L3043} 
+\section{File Organization}
+
+A file consists of sections that should be separated by blank lines
+and an optional comment identifying each section.
+
+Files longer than 2000 lines are cumbersome and should be avoided.
+
+For an example of a properly formatted program, see
+Source File Example (section \ref{L182}).
+
+\label{L11684} 
+\subsection{Source Files}
+
+\label{Lfile_h}
+\subsubsection{Include Files}
+
+\emph{\XXX{} I added this}\hfil\break
+Header files should have names starting \code{ps} or
+\code{p_ps} for private interface definitions. The latter
+should appear in a subdirectory \code{private} of whichever
+directory it being searched for the public header files.
+
+Include files should have the following order:
+\begin{itemize}
+\item 
+A check for the existance of a CPP symbol of the form
+\code{FILENAME_H} (e.g. \code{STDIO_H}). This is used
+to ensure that an include file may safely be included more than once.
+
+\item 
+A brief description of the functionality provided by this set of APIs.
+This comment should not duplicate information available
+elsewhere (e.g. the filename; log information available from cvs).
+
+\item 
+Any \code{#define}d constants. N.b. \code{#define} should be used rather
+than e.g. \code{const int}; C and C++ const semantics are different.
+
+\item 
+Any typedefs.
+\XXX{} describe use of typedefs.
+
+\item 
+Any function prototypes.
+
+\end{itemize}
+e.g. for file \file{psThing.h}:
+\begin{verbatim}
+#if !defined(PS_THING_H)
+#define PS_THING_H
+/*
+ * Support for psThings
+ */
+#define PS_NMAX 10                      /* maximum number of subthings */
+
+typedef struct {
+  int nthing;                           /* number of subthings */
+  int sthing[PS_NMAX];                  /* the subthings */
+} psThing;
+
+psThing *psThingNew(int nthing);
+void psThingDel(psThing *thing);
+
+#endif
+\end{verbatim}
+
+\label{Lfile_c}\subsubsection{C Source Files}
+
+C Source files have the following ordering:
+\begin{itemize}
+\item Beginning comments, concisely describing the functionality present
+in the file.  This comment should not duplicate information available
+elsewhere (e.g. the filename; log information available from cvs).
+
+\item \code{#include} statements
+
+\item \code{#defines} local to the file
+
+\item Typedefs local to the file
+
+\item Any needed prototypes for file-static functions. Prototypes need
+only be provided for functions used before their definition; in practice
+this means ones that the compiler complains about.
+
+\item File-static variable declarations
+
+\item The code that actually implements the desired functionality.
+\end{itemize}
+
+\label{Lfile_i}\subsubsection{SWIG Interface Files}
+
+\XXX{} Write me
+
+%------------------------------------------------------------------------------
+
+\label{L262} 
+\section{Indentation}
+
+Two spaces should be used as the unit of indentation. The exact
+construction of the indentation (spaces vs. tabs) is unspecified. Tabs
+must be set exactly every 8 spaces (not 2).
+
+\label{L313} 
+\subsection{Line Length}
+
+Avoid lines longer than 80 characters, since they're not handled well by many terminals and tools.
+
+Note: Examples for use in documentation should have a shorter line length-generally no more than 70 characters.
+
+\label{L248} 
+\subsection{Wrapping Lines}
+
+When an expression will not fit on a single line, break it according
+to these general principles:
+
+\begin{itemize}
+\item Break after a comma.
+
+\item Break before an operator.
+
+  \emph{ \XXX{} RHL prefers to break \textit{after} an operator}, e.g.
+\begin{verbatim}
+if(a < b ||
+   a > 2*b) {
+  x = (a + b + c) +
+    sin(z);
+}
+\end{verbatim}
+not
+\begin{verbatim}
+if(a < b
+   || a > 2*b) {
+  x = (a + b + c)
+    + sin(z);
+}
+\end{verbatim}
+as the former tells the reader more directly that it's a partial
+statement.  Do we want to modify these rules?
+
+\item Prefer higher-level breaks to lower-level breaks.
+
+\item Align the new line with the beginning of the expression at the
+same level on the previous line (for emacs users, this means the
+indentation that \code{<tab>} produces. If this isn't helpful to
+the majority of the people writing code for pan-STARRS, we can
+be more formal about what this rule means).
+
+\item If the above rules lead to confusing code or to code that's squished up against the right margin, just indent 8 spaces instead.
+\hfil\break\emph{\XXX{} emacs actually just uses a regular 2 space indent;
+should we do the same? }
+\end{itemize}
+
+Here are some examples of breaking function calls:
+
+\begin{verbatim}
+someFunc(longExpression1, longExpression2, longExpression3, 
+        longExpression4, longExpression5);
+ 
+var = someFunc1(longExpression1,
+                someFunc2(longExpression2,
+                        longExpression3)); 
+\end{verbatim}
+
+Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.
+
+\begin{verbatim}
+longName1 = longName2 * (longName3 + longName4 - longName5)
+           + 4 * longname6; // PREFER
+
+longName1 = longName2 * (longName3 + longName4
+                       - longName5) + 4 * longname6; // AVOID 
+\end{verbatim}
+
+Following are two examples of indenting function declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces.
+\begin{verbatim}
+//CONVENTIONAL INDENTATION
+void someFunc(int anArg, Object anotherArg, String yetAnotherArg,
+              Object andStillAnother)
+{
+    ...
+}
+
+//INDENT 8 SPACES TO AVOID VERY DEEP INDENTS
+static type honkingLongFunctionName(int anArg,
+        Object anotherArg, String yetAnotherArg,
+        Object andStillAnother)
+{
+    ...
+}
+\end{verbatim}
+
+Line wrapping for \code{if} statements should generally use the
+8-space rule, since conventional (2 space) indentation makes seeing
+the body difficult. For example:
+\begin{verbatim}
+//DON'T USE THIS INDENTATION
+if ((condition1 &amp;&amp; condition2)
+    || (condition3 &amp;&amp; condition4)
+    ||!(condition5 &amp;&amp; condition6)) { //BAD WRAPS
+    doSomethingAboutIt();            //MAKE THIS LINE EASY TO MISS
+} 
+
+//USE THIS INDENTATION INSTEAD
+if ((condition1 &amp;&amp; condition2)
+        || (condition3 &amp;&amp; condition4)
+        ||!(condition5 &amp;&amp; condition6)) {
+    doSomethingAboutIt();
+} 
+
+//OR USE THIS
+if ((condition1 &amp;&amp; condition2) || (condition3 &amp;&amp; condition4)
+        ||!(condition5 &amp;&amp; condition6)) {
+    doSomethingAboutIt();
+} 
+\end{verbatim}
+Here are three acceptable ways to format ternary expressions:
+\begin{verbatim}
+alpha = (aLongBooleanExpression) ? beta : gamma;  
+
+alpha = (aLongBooleanExpression) ? beta
+                                 : gamma;  
+
+alpha = (aLongBooleanExpression)
+        ? beta 
+        : gamma;  
+\end{verbatim}
+
+%------------------------------------------------------------------------------
+
+\label{L385} 
+\section{Comments}
+
+C99 supports both types of comments found
+in C++, namely those delimited by /*...*/, and //.
+
+Comments should not be used to `comment out code'; use \code{#if 0} instead:
+\begin{verbatim}
+#if 0
+  code that is not wanted just at present
+#endif
+\end{verbatim}
+This has two advantages:
+\begin{itemize}
+\item  The code can easily be reinstated.
+\item  Related blocks of code can be removed with
+\begin{verbatim}
+#define IGNORE_RHL 1
+#if !IGNORE_RHL
+  ...
+#endif
+...
+#if !IGNORE_RHL
+  ...
+#endif
+\end{verbatim}
+This type of \code{#define} may appear within the main body of the file.
+\end{itemize}
+
+\emph{\XXX{} RHL added this.  He stands by it. }
+
+Comments should be used to give overviews of code and provide
+additional information that is not readily available in the code
+itself. Comments should contain only information that is relevant to
+reading and understanding the program. For example, information about
+how the corresponding package is built or in what directory it resides
+should not be included as a comment.
+
+Discussion of nontrivial or nonobvious design decisions is
+appropriate, but avoid duplicating information that is present in (and
+clear from) the code. It is too easy for redundant comments to get out
+of date. In general, avoid any comments that are likely to get out of
+date as the code evolves.
+
+Note:The frequency of comments sometimes reflects poor quality of
+code. When you feel compelled to add a comment, consider rewriting the
+code to make it clearer.
+
+Comments should not be enclosed in large boxes drawn with asterisks or
+other characters.
+\hfil\break
+Comments should never include special characters such as form-feed and
+backspace.
+ 
+\label{L216} 
+\subsection{Implementation Comment Formats}
+
+Programs can have four styles of implementation comments: block, single-line, trailing, and end-of-line. 
+\label{L680} 
+\subsubsection{Block Comments }
+
+Block comments are used to provide descriptions of files, functions,
+data structures and algorithms. Block comments may be used at the
+beginning of each file and before each function. They can also be used
+in other places, such as within functions. Block comments inside a
+function should be indented to the same level as the code they
+describe.
+
+\emph{\XXX{} I don't see any reason for this blank line}\hfil\break
+A block comment should be preceded by a blank line to set it apart from the rest of the code. 
+\begin{verbatim}
+/*
+ * Here is a block comment.
+ */
+\end{verbatim}
+
+See also Documentation Comments (section \ref{L16838}).
+
+\label{L341} 
+\subsubsection{Single-Line Comments}
+
+Short comments can appear on a single line indented to the level of
+the code that follows. If a comment can't be written in a single line,
+it should follow the \ref{L680}block comment format. A
+single-line comment should be preceded by a blank line.
+\emph{\XXX{} I don't see any reason for this blank line}\hfil\break
+Here's an
+example of a single-line comment in C code (also see \ref{L16838}''Documentation Comments''):
+
+\begin{verbatim}
+if (condition) {
+
+  /* Handle the condition. */
+  ...
+}
+\end{verbatim}
+
+\label{L342} 
+\subsubsection{Trailing Comments}
+
+Very short comments can appear on the same line as the code they
+describe, and should be indented to column 40 (in emacs, this
+may be achieved with \code{ESC;}). If the code extends beyond
+this column, the comment should be separated from the closing semi-colon
+by a single space.
+
+Here's an example of a trailing comment in C code: 
+\begin{verbatim}
+if (a == 2) {
+  return TRUE;                          /* special case */
+} else {
+  return isPrime(a);                    /* works only for odd a */
+}
+\end{verbatim}
+
+\label{L286} 
+\subsubsection{End-Of-Line Comments}
+
+The \code{//} comment delimiter can comment out a complete line
+or only a partial line; as for trailing comments, the comment should
+start in column 40.  It shouldn't be used on consecutive multiple
+lines for text comments.  Examples of both styles follow:
+
+\begin{verbatim}
+if (foo &gt; 1) {
+
+  // Do a double-flip.
+  ...
+} else {
+  return false;          // Explain why here.
+}
+\end{verbatim}
+
+\label{L16838} 
+\subsection{Documentation Comments}
+
+\emph{\XXX{} Need references to Doxygen here.}
+
+If you need to give information about a type, interface, or variable
+that isn't appropriate for doxygenation, use an implementation block
+comment (sec. \ref{L680}) or single-line comment (sec. \ref{L341})
+immediately \textit{before} the code. For example, details about the
+implementation of a type should go in in such an implementation block
+comment \textit{before} the start of the implementation, not in the
+doxygen comment.
+
+%------------------------------------------------------------------------------
+
+\label{L2991} 
+\section{Declarations}
+
+\emph{\XXX{} I added this}\hfil\break
+\textit{All globally-visible symbols must be declared in
+a suitable header (.h) file.}.  Global private symbols (i.e.
+those named \code{p_ps}) should not appear in public header
+files, but rather in files whose names begin \code{p_ps}.
+
+\label{L2992} 
+\subsection{Number Per Line}
+
+One declaration per line is recommended since it encourages commenting. In other words,
+\begin{verbatim}
+int level;                              // indentation level
+int size;                               // size of table
+\end{verbatim}
+is preferred over
+\begin{verbatim}
+int level, size;
+\end{verbatim}
+Do not put different types on the same line. Example:
+\begin{verbatim}
+int foo,  fooarray[];                   //WRONG!
+\end{verbatim}
+
+Note: The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs, e.g.:
+\begin{verbatim}
+int    level;                           // indentation level
+int    size;                            // size of table
+Object    currentEntry;                 // currently selected table entry
+\end{verbatim}
+
+(Note that the comments are indented to column 40).
+
+\label{L18761} 
+\subsection{Initialization}
+
+Try to initialize local variables where they're declared.
+\hfil\break\emph{\XXX{} the following is invalidated by the rewrite of section 6.3}
+The only
+reason not to initialize a variable where it's declared is if the
+initial value depends on some computation occurring first.
+
+\hfil\break\emph{\XXX{} added by RHL}
+In some cases it may be necessary to initialize a variable to suppress
+a compiler warning; in this case a comment should explain the circumstances.
+
+\label{L16817} 
+\subsection{Placement}
+
+\hfil\break\emph{\XXX{} I've changed this}
+
+Variables should ordinarily be declared as soon as they 
+appear in the logical flow of control through a function. This
+allows them to be initialised as they are created, and naturally
+associates their declaration with their use.
+
+In particular, indexes of \code{for} loops should usually
+be declared in the \code{for} statement (the declarations appear
+in the scope of the braces):
+\begin{verbatim}
+for (int i = 0; i &lt; maxLoops; i++) {
+  ...
+}
+\end{verbatim}
+
+\hfil\break\emph{\XXX{} OLD VERSION}
+
+Put declarations at the beginning of blocks. (A block is any code
+surrounded by curly braces \CODE.{. and \CODE.}..) Don't wait to declare
+variables until their first use; it can confuse the unwary programmer
+and hamper code portability within the scope.
+
+\begin{verbatim}
+void myFunction(void)
+{
+  int int1 = 0;                         // beginning of function block
+
+  if (condition) {
+    int int2 = 0;                       // beginning of "if" block
+    ...
+  }
+}
+\end{verbatim}
+
+One exception to the rule is indexes of \code{for} loops, which
+in C99 can be declared in the \code{for} statement (and which appear
+in the scope of the braces):
+\begin{verbatim}
+for (int i = 0; i &lt; maxLoops; i++) {
+  ...
+}
+\end{verbatim}
+
+p>
+
+\emph{\XXX{} Added by RHL: }\hfil\break
+Another exception is that assertions may preceed or be mixed with declarations:
+\begin{verbatim}
+void function(REGION *reg)                      // image of the sky
+{
+  assert (reg != NULL);
+  const int nrow = reg->nrow;
+  assert (reg->type == psType_U16);
+  const psTypeU16 *rows = reg->rows;
+  ...
+}
+\end{verbatim}
+Note that this allows us to declare variables that have been unpacked
+to e.g. allow dealiasing to be declared \code{const}.
+
+\hfil\break\emph{\XXX{} End old version }
+
+Avoid local declarations that hide declarations at higher levels. For
+example, do not declare the same variable name in an inner block:
+\begin{verbatim}
+static int count;
+...
+void myFunction(void)
+{
+  if (condition) {
+    int count = 0;                      // AVOID!
+    ...
+  }
+  ...
+}
+\end{verbatim}
+
+\label{L381} 
+\subsection{Function Declarations}
+
+When coding C functions the following formatting rules should be
+followed:
+
+\begin{itemize}
+\item 
+Function declarations should be preceeded by a short comment
+describing what the function does. \hfil\break\emph{\XXX{} Doxygen? }
+
+\item The function's type should appear on the same line as the
+function declaration.
+\hfil\break\emph{\XXX{} I don't like this (I put the type
+on the previous line), but MHPCC seems to use it}
+
+\item All arguments should be declared with their types; i.e. no
+classic-C declarations like:
+\begin{verbatim}
+int main(ac, av)
+         int ac;
+         char **av;
+\end{verbatim}
+
+\item No space between a function name and the parenthesis \code{(} starting
+its parameter list \matchBracket{)}
+
+\item The function body's open brace \CODE.{. should be in column 1 of the next line:
+\begin{verbatim}
+void function(void)
+{
+  ...
+}
+\end{verbatim}
+
+\item Closing brace \CODE.}. starts a line by itself indented to match its
+corresponding opening statement, except when it is a null statement
+the \CODE.}. should appear immediately after the \CODE.{..
+
+\begin{verbatim}
+void find_neos(const REGION *sky,       // bregion to search
+               const char *descrip      // work orders
+               )
+{
+  struct {
+      int x, y;
+  } work[10];
+  int ivar;
+
+  while(isspace(*descrip++)) {}         // skip white space
+  descrip--;                            // one too far. Not great code...
+
+  ...
+}
+\end{verbatim}
+\end{itemize}
+
+%------------------------------------------------------------------------------
+
+\label{L430} 
+\section{Statements}
+\label{L431} 
+\subsection{Simple Statements}
+
+Each line should contain at most one statement. Example:
+\begin{verbatim}
+argv++;                                 // Correct
+argc--;                                 // Correct  
+argv++; argc--;                         // AVOID!
+\end{verbatim}
+
+\label{L15395} 
+\subsection{Compound Statements}
+
+Compound statements are statements that contain lists of statements
+enclosed in braces. See the
+following sections for examples.
+
+\begin{itemize}
+\item The enclosed statements should be indented one more level than the compound statement.
+
+\item The opening brace should be at the end of the line that begins
+the compound statement; the closing brace should begin a line and be
+indented to the beginning of the compound statement.
+
+\item Braces are used around all statements, even single statements,
+when they are part of a control structure, such as a \code{if-else} or
+\code{for} statement. This makes it easier to add statements without
+accidentally introducing bugs due to forgetting to add braces.
+\end{itemize}
+
+\label{L438} 
+\subsection{return Statements}
+
+A \code{return} statement with a value should not use parentheses unless they make the return value more obvious in some way. Example:
+\begin{verbatim}
+return;
+
+return myDisk.size;
+
+return (size ? size : defaultSize);
+
+\end{verbatim}
+
+\label{L449} 
+\subsection{if, if-else, if else-if else Statements}
+
+The \code{if-else} class of statements should have the following form:
+\begin{verbatim}
+if (condition) {
+  statements;
+}
+
+if (condition) {
+  statements;
+} else {
+  statements;
+}
+
+if (condition) {
+  statements;
+} else if (condition) {
+  statements;
+} else {
+  statements;
+}
+
+\end{verbatim}
+
+Note: \code{if} statements always use braces {}. Avoid the following error-prone form:
+\begin{verbatim}
+if (condition) //AVOID! THIS OMITS THE BRACES {}!
+    statement;
+\end{verbatim}
+
+\label{L454} 
+\subsection{for Statements}
+
+A \code{for} statement should have the following form:
+\begin{verbatim}
+for (initialization; condition; update) {
+  statements;
+}
+\end{verbatim}
+
+An empty \code{for} statement (one in which all the work is done
+in the initialization, condition, and update clauses) should have the
+following form:
+\begin{verbatim}
+for (initialization; condition; update);
+\end{verbatim}
+
+When using the comma operator in the initialization or update clause
+of a \code{for} statement, avoid the complexity of using more
+than three variables. If needed, use separate statements before the
+\code{for} loop (for the initialization clause) or at the end of
+the loop (for the update clause).
+
+\label{L460} 
+\subsection{while Statements}
+
+A \code{while} statement should have the following form:
+\begin{verbatim}
+while (condition) {
+  statements;
+}
+\end{verbatim}
+An empty \code{while} statement should have the following form:
+\begin{verbatim}
+while (condition);
+\end{verbatim}
+
+\label{L465} 
+\subsection{do-while Statements}
+
+A \code{do-while} statement should have the following form:
+\begin{verbatim}
+do {
+  statements;
+} while (condition);
+\end{verbatim}
+
+
+\emph{\XXX{} RHL would prefer that we mandate one of the forms}:
+\begin{verbatim}
+for (initialization; condition; update) {}
+for (initialization; condition; update) continue;
+\end{verbatim}
+Ditto for \code{while} statements.  The closing ; is subtle,
+especially bearing in mind:
+\begin{verbatim}
+do {
+    ....
+while (condition);
+\end{verbatim}
+where the while really does have a closing semicolon.
+
+\label{L468} 
+\subsection{switch Statements}
+
+A \code{switch} statement should have the following form:
+\begin{verbatim}
+switch (condition) {
+case ABC:
+  statements;
+  /* falls through */
+
+case DEF:
+case GHI:
+  statements;
+  break;
+
+case XYZ:
+  statements;
+  break;
+
+default:
+  statements;
+  break;
+}
+\end{verbatim}
+
+\emph{\XXX{} I'd prefer to indent the ``case'' 1 more spaces RHL}:
+\begin{verbatim}
+switch (condition) {
+ case ABC:
+  statements;
+  /* falls through */
+
+ case DEF:
+ case GHI:
+  statements;
+  break;
+
+ case XYZ:
+  statements;
+  break;
+
+ default:
+  statements;
+  break;
+}
+\end{verbatim}
+
+Every time a case falls through (doesn't include a \code{break}
+statement), add a comment where the \code{break} statement would
+normally be. This is shown in the preceding code example with the
+ \code{/* falls through */} comment. A comment is not
+required (or expected) when the fall-through is between multiple case
+statements.
+
+Every \code{switch} statement should include a default case,
+which should come last. The \code{break} in the default case
+is redundant, but it prevents a fall-through error if later another
+\code{case} is later (and illegally) added after the default clause.
+
+\emph{ \XXX{} Added by RHL}\hfil\break
+When switching on an enumerated type, if all the elements of the
+type are included in the switch a default clause should still be
+added (not all compilers diagnose missing elements).  In this case,
+the action in the default clause should be to generate an error
+and abort.
+
+%------------------------------------------------------------------------------
+
+\label{L475} 
+\section{White Space}
+\label{L487} 
+\subsection{Blank Lines}
+
+Blank lines improve readability by setting off sections of code that
+are logically related.
+
+Two blank lines should always be used in the following circumstances:
+\begin{itemize}
+\item Between sections of a source file
+\end{itemize}
+
+One blank line should always be used in the following circumstances:
+
+\begin{itemize}
+
+\item Between the local variables in a function and its first statement
+
+\item Before a \ref{L680}block or \ref{L341}single-line comment
+
+\item Between logical sections inside a function to improve readability
+\end{itemize}
+
+\label{L682}
+\subsection{Blank Spaces}
+
+Blank spaces should be used in the following circumstances:
+\begin{itemize}
+
+\item A keyword followed by a parenthesis should be separated by a space. Example:
+\begin{verbatim}
+while (true) {
+  ...
+}
+\end{verbatim}
+
+Note that a blank space should not be used between a function name and
+its opening parenthesis. This helps to distinguish keywords from
+function calls.
+
+\item A blank space should appear after commas in argument lists.
+
+\item All binary operators except \code{.} and \code{->}
+should be separated from their operands by spaces. Blank spaces should
+never separate unary operators such as unary minus, increment (\code{++}),
+and decrement (\code{--}) from their operands. Example:
+\begin{verbatim}
+  a += c + d;
+  a = (a + b) / (c * d);
+    
+  while (*d++ = *s++) {                 // Tricky way of copying to '\0'
+      n++;
+  }
+  printf("size is %d\n", foo);
+\end{verbatim}
+\hfil\break\emph{ \XXX{} I had to fix the code to make it even make sense, but it's
+still lousy code (I admit that you'll see it in K\&R, but it's a very
+1970s style)}
+\hfil\break\emph{\XXX{} I don't like this either.  I'd prefer to see multiplicative
+operators (i.e. * / \%) without whitespace.  E.g.}
+\begin{verbatim}
+a%x + y;
+a*(x + y);
+(a + b)/(x + y);
+\end{verbatim}
+
+\item The expressions in a \code{for} statement should be
+separated by blank spaces. Example:
+
+\begin{verbatim}
+    for (expr1; expr2; expr3)
+\end{verbatim}
+\item Casts should be followed by a blank space. Examples: 
+\begin{verbatim}
+    myFunc((byte) aNum, (Object) x);
+    myFunc((int) (cp + 5), ((int) (i + 3)) 
+                                  + 1);
+\end{verbatim}
+
+\hfil\break\emph{\XXX{} I really don't like this one.  A cast is a unary operator,
+and binds harder than e.g. ++. }
+
+\item 
+\emph{\XXX{} I added this }\hfil\break
+The word \code{assert} should be treated as a keyword, and
+separated by a space from its logical expression.
+\end{itemize}
+
+%------------------------------------------------------------------------------
+
+\label{L367} 
+\section{Naming Conventions}
+
+Naming conventions make programs more understandable by making them
+easier to read. They can also give information about the function of
+the identifier -- for example, whether it's a constant, a function, or
+a type -- which can be helpful in understanding the code.
+ 
+\begin{tabular}{lp{3in}p{3in}}
+\textbf{Identifier Type} &
+\textbf{Rules for Naming} &
+\textbf{Examples} \\
+
+Typedefs &
+
+Type names should be nouns, in mixed case with the first letter of
+each internal word capitalized.
+
+If and only if the type is visible at global scope, the
+type name should start with \code{ps}.
+
+Try to keep your type names simple and descriptive. Use whole
+words-avoid acronyms and abbreviations (unless the abbreviation is
+much more widely used than the long form, such as URL or HTML).
+
+ &
+typedef struct {...} psRaster;\hfil\break
+typedef struct {...} psImage;
+\\
+
+Functions &
+
+The names of all externally visible functions (i.e. all those that are
+not declared \code{static}) should be verbs, in mixed case. The
+first two characters should be \code{ps}, with the first letter
+of each internal word capitalized.
+
+Functions that are visible at global scope but are not considered part
+of the public interface should be prefixed \code{p_ps}.
+
+Functions that are local to a file should \textit{not} start
+\code{ps} (or \code{p_ps}).
+ 
+&
+
+\code{psRun(int ID);}\hfil\break
+\code{psRunFast(float velocity);}\hfil\break
+\code{psGetBackground(void);}\hfil\break
+\hfil\break
+\code{p_psForgeSignature(const char *name);}
+
+\\
+
+Variables &
+
+Except for variables, all instance, class, and class constants are in
+mixed case with a lowercase first letter. Internal words start with
+capital letters. Variable names should not start with underscore \code{_}
+as these names are, under some circumstances, reserved by the
+C standard.
+
+Variables visible at global scope should begin with \code{ps},
+or \code{p_ps} if not considered part of the public interface.
+Variables that are local to a file should \textit{not} start
+with \code{ps} (or \code{p_ps}).
+
+Variable names should be short yet meaningful. The choice of a
+variable name should be mnemonic- that is, designed to indicate to the
+casual observer the intent of its use. One-character variable names
+should be avoided except for temporary \textit{throwaway} variables. Common
+names for temporary variables are \code{i}, \code{j},
+\code{k}, \code{m}, and \code{n} for integers;
+\code{c}, \code{d}, and \code{e} for characters.
+
+&
+\code{int i; char c; float myWidth;}\hfil\break
+\hfil\break
+\code{int psNumOTA;}\hfil\break
+\code{int p_psMyFiddleFactor;}\hfil\break
+
+\\
+ 
+Constants
+
+&
+
+\emph{\XXX{} const is different in C from Java (and C++) so I've rewritten
+this.}\hfil\break
+
+Constants used to e.g. dimension arrays should be set using
+the \code{#define}; \code{const} variables should not be used, especially
+in header files.  Symbolic values should usually be declared using
+enumerated types (although this requires more care with namespaces).
+
+The names of all enumerated types and C-preprocessor symbols (but not
+variables declared \code{const}) declared should start with
+\code{PS_} or \code{P_PS_} and the rest of the name should
+be uppercase with words separated by underscores (\code{_}). In the case of
+system utilities implemented as macros, the names may conform to the
+usual Pan-STARRS conventions (e.g. \code{psAlloc}).
+
+&
+\code{#define PS_MAXLEN 40}\hfil\break
+\CODE|enum { PS_ONE = 1, PS_TWO = 2 };|\hfil\break
+
+\end{tabular}
+
+%------------------------------------------------------------------------------
+
+\label{L529} 
+\section{Programming Practices}
+
+\label{L177} 
+\subsection{When to Make Symbols Global}
+
+Declare all functions and variables \code{static} within a
+file if at all possible (n.b. do not confuse this use of \code{static}
+with its usage to make auto-variables within a function persistent).
+
+\label{L1255} 
+\subsection{Constants}
+
+Numerical constants (literals) should not be coded directly, except for
+small integers such as -1, 0, and 1 which are permitted to e.g. appear
+in a \code{for} loop as counter values.  
+
+\emph{ \XXX{} RHL relaxed this a little}
+
+\label{L547} 
+\subsection{Variable Assignments}
+
+Avoid assigning several variables to the same value in a single
+statement, unless the variables are intimately related. Example:
+
+\begin{verbatim}
+fChar = lchar = 'c';                    // AVOID!
+row0 = col0 = 0;                        // OK
+\end{verbatim}
+\emph{\XXX{} Relaxed by RHL}
+
+Do not use the assignment operator in a place where it can be easily confused with the equality operator. Example:
+\begin{verbatim}
+if (c++ = d++) {                        // AVOID!
+  ...
+}
+\end{verbatim}
+should be written as
+\begin{verbatim}
+if ((c++ = d++) != 0) {
+  ...
+}
+\end{verbatim}
+If \code{c} and \code{d} are char variables, use \code{'\0'}
+instead of \code{0}.
+\hfil\break\emph{\XXX{} \code{'$\backslash$0'} added by RHL}
+
+Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. Example:
+\begin{verbatim}
+d = (a = b + c) + r;                    // AVOID!
+\end{verbatim}
+
+should be written as
+\begin{verbatim}
+a = b + c;
+d = a + r;
+\end{verbatim}
+
+\label{L554} 
+\subsection{Miscellaneous Practices}
+\label{L331} 
+\subsubsection{Parentheses}
+
+It is generally a good idea to use parentheses liberally in
+expressions involving mixed operators to avoid operator precedence
+problems. Even if the operator precedence seems clear to you, it might
+not be to others-you shouldn't assume that other programmers know
+precedence as well as you do.
+
+\begin{verbatim}
+if (a == b && c == d)                   // AVOID!
+if ((a == b) && (c == d))               // RIGHT
+\end{verbatim}
+\hfil\break\emph{\XXX{} I don't agree with this; you end up with
+too many parens.  Next section is added by RHL}
+
+There are some famous problems with precedence in C.  In particular,
+expressions involving the combinations of \code{||} and
+\code{\&\&} should be parenthesised as should all
+expressions containing bitwise operators:
+\begin{verbatim}
+if ((a == b \&\& c == d) || e == f)
+l << (j + k)
+(l << j) + k
+(i & b) | c
+\end{verbatim}
+
+\label{L333} 
+\subsubsection{Returning Values}
+
+Try to make the structure of your program match the intent. Example:
+\begin{verbatim}
+if (booleanExpression) {
+  return true;
+} else {
+  return false;
+}
+\end{verbatim}
+should instead be written as
+\begin{verbatim}
+return booleanExpression;
+\end{verbatim}
+If you're concerned that the reader may not know that
+\code{booleanExpression} is boolean, use:
+\begin{verbatim}
+return (booleanExpression ? true : false);
+\end{verbatim}
+
+Similarly,
+\begin{verbatim}
+if (condition) {
+  return x;
+}
+return y;
+\end{verbatim}
+should be written as
+\begin{verbatim}
+return (condition ? x : y);
+\end{verbatim}
+
+\label{L353} 
+\subsubsection{Expressions before `?' in the Conditional Operator }
+
+If an expression containing a binary operator appears before the \code{?} in the ternary \code{?: }operator, it should be parenthesized. Example:
+\begin{verbatim}
+(x &gt;= 0) ? x : -x;
+\end{verbatim}
+
+\label{L396} 
+\subsubsection{Functions that Take No Parameters}
+
+\emph{\XXX{} added by RHL}
+
+When a function takes no arguments, it should be explicitly declared
+as \code{void}:
+\begin{verbatim}
+static type myFunction(void)
+{
+  ...
+}
+\end{verbatim}
+
+
+\label{L395} 
+\subsubsection{Special Comments}
+\begin{itemize}
+\item 
+Use \code{\XXX{}} in a comment to flag something that is bogus but works.
+
+\item 
+Use \code{FIXME} to flag something that is bogus and broken.
+
+\emph{\XXX{} next items added by RHL}
+
+\item 
+Use \code{NOTREACHED} to indicate a line of code that cannot be reached,
+e.g.
+\begin{verbatim}
+if (sqrt(x) < 0) {
+  psAbort();                            // never returns
+  exit(1);                              // NOTREACHED
+}
+\end{verbatim}
+
+\item 
+Use \code{NOTUSED} to indicate unused arguments to a function:
+e.g.
+\begin{verbatim}
+type psWorkHard(const Region *restrict reg, // Region to operate on
+                int myConst,            // magic value
+                int magicNumber         // NOTUSED; reserve for next version
+                )
+{
+   ...
+}
+\end{verbatim}
+
+\emph{\XXX{} I see some @notused@ comments in the MHPCC code. Is this
+usage documented? Should we adopt it?}
+\end{itemize}
+
+\subsubsection{\label{LNewDel}10.4.6     Constructors/Destructors}
+
+\emph{\XXX{} Added by RHL }
+
+Type definitions should always be accompanied by prototypes for
+their constructors and destructors:
+
+\begin{itemize}
+\item  The constructor should consist of the type name followed by
+\code{New}; e.g. a type \code{psImage} would
+be created by a function
+\begin{verbatim}
+psImage *psImageNew(int nrow, int ncol);
+\end{verbatim}
+
+\item  Similarly, the type should be freed with a destructor named
+\code{typeDel}, e.g.
+\begin{verbatim}
+void psImageDel(psImage *img);
+\end{verbatim}
+
+\item  The constructor should never return \code{NULL}, and
+no code calling the constructor should ever check the return value.
+
+\item  The destructor must not return a value.
+
+\item  The destructor should handle being passed \code{NULL}
+by simply returning immediately. This should not be treated as
+an error condition.
+
+\end{itemize}
+
+\subsection{\label{LConvOps}Naming Conversion Operators}
+
+\emph{\XXX{} Added by RHL }
+
+When defining a function to convert from one type to another, the
+name should be of the form \code{psOldToNew}, e.g.
+\code{psEquatorialToEcliptic}.
+
+\subsection{\label{LArgumentOrder}Order of I/O Arguments}
+
+\emph{\XXX{} Added by RHL }
+
+Functions that assign to a variable should list that argument
+\textit{first} (i.e. following the pattern of \code{strcpy}):
+
+\subsection{\label{LConstRestrict}Type Qualifiers (const and restrict)}
+
+\emph{\XXX{} Added by RHL }
+
+All interfaces and type definitions should use \code{const} and
+\code{restrict} wherever appropriate. For example,
+\begin{verbatim}
+typedef struct {
+  int n;
+  float *restrict vec;
+} psVec;
+
+psVec *psVecAdd(const restrict* psVec s1, const restrict* psVec s2); 
+\end{verbatim}
+
+\textit{N.b. compilers are free to ignore the \code{restrict} keyword,
+so all code should be written to explicitly handle aliasing}.
+
+\emph{\XXX{} Sadly, it looks to me as if gcc 3.3 doesn't make
+serious use of \code{restrict}.  I believe that we should
+still encourage its use.}
+
+%------------------------------------------------------------------------------
+
+\label{L186} 
+\section{Code Examples}
+\label{L182} 
+\subsection{Source File Example}
+
+\begin{verbatim}
+/*
+ * This file implements an example of formatting a C
+ *
+ * It isn't a very good piece of code
+ */
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+#include <time.h>
+#include "psUtils.h"
+
+#define BUFSIZE 128                     // Size for I/O buffers
+
+typedef struct {
+  char buf[BUFSIZE];                    // buffer
+  int n;                                // number of bytes in buffer
+} Buffer;
+
+typedef enum { NL, CRNL, CR } NLType;
+
+static void addNewline(NLType type);    // add a newline to the buffer
+
+static Buffer *buf = NULL;              // I/O buffer
+
+/*****************************************************************************/
+/*
+ * Create/destroy Buffers
+ */
+static Buffer *bufferNew(void)
+{
+  Buffer *buf = psAlloc(sizeof(Buffer));
+  buf->n = 0;
+
+  return buf;
+}
+
+void bufferDel(Buffer *buf,             // buffer to delete
+               int deep)                // NOTUSED. Do a deep delete
+{
+  if (buf == NULL) {
+    return;
+  }
+    
+  if (buf->n > 0) {
+    (void) fputs(buf->buf, stdout);
+  }
+    
+  psFree(buf);
+}
+
+/*****************************************************************************/
+/*
+ * Append to a string to a Buffer
+ */
+static void bufferAppend(Buffer *restrict buf, // Buffer to append to
+                         const char *restrict str) // string to add
+{
+  assert(str != NULL);
+  const int len = strlen(str);
+
+  if (buf->n + len >= BUFSIZE) {        // XXX Handle this better
+    fprintf(stderr,"Sorry; too many bytes. Bye bye\n");
+    abort();
+    exit(1);                    // NOTREACHED
+  }
+
+  (void) strcat(&buf->buf[buf->n], str);
+  buf->n += len;
+}    
+
+/*****************************************************************************/
+/*
+ * Now do the work
+ */
+int main(void)
+{
+  buf = bufferNew();
+  long t;                               // current time
+
+  while(t = (long)time(NULL), t % 4 != 2) {}
+    
+  if (t % 4 == 0) {
+    bufferAppend(buf, "Hello");
+  } else if (t % 4 == 1) {
+    bufferAppend(buf, "Bonjour");
+  } else {
+    bufferAppend(buf, "Aloha");
+  }
+  bufferAppend(buf, " World!");
+
+  addNewline(NL);
+
+  bufferDel(buf, 0);
+
+  return 0;
+}
+
+/*****************************************************************************/
+/*
+ * Add a newline to the buffer
+ */
+static void addNewline(NLType type)             // what sort of newline?
+{
+  char *newline;                        // newline to add
+  switch (type) {
+   case NL:
+    newline = "\n";
+    break;
+
+   case CRNL:
+    newline = "\r\n";
+    break;
+
+   case CR:
+    newline = "\r";
+    break;
+
+   default:
+    newline = "NL";                     // FIXME
+    break;
+  }
+
+  bufferAppend(buf, newline);
+}
+\end{verbatim}
+
+%------------------------------------------------------------------------------
+
+\section{How to Achieve This Style in Emacs}
+  \label{dot_emacs}
+
+\textit{This section is provided for your convenience, it is of course
+not part of the coding standards.}
+
+If you want to simply set these variables you can, see the code in
+the section on hooks (section \ref{Lhooks}) below.
+
+\subsection{\label{Lusing customize}Using Customize to Control Formatting}
+
+Add this to your \file{.emacs} file:
+\begin{verbatim}
+(custom-set-variables
+  ;; custom-set-variables was added by Custom -- don't edit or cut/paste it!
+  ;; Your init file should contain only one such instance.
+ '(c-basic-offset 2)
+ '(c-default-style (quote ((other . "k\&r"))))
+ '(c-offsets-alist (quote ((statement-case-intro . 1) (statement-case-open . 1) (case-label . 1))))
+ '(comment-column 40)
+ )
+\end{verbatim}
+
+If you already have a
+\code{custom-set-variables} command be careful! Or set the same values
+using the \code{Customize Emacs} entry in the \code{Options} menu,
+then follow down:
+\begin{verbatim}
+Browse Customization Groups -->
+    Programming -->
+        Languages -->
+            C
+\end{verbatim}
+(an alternative way to get to the same place is
+\begin{verbatim}
+ESCx
+customize-group
+C
+\end{verbatim}
+)
+Then set the values of
+\begin{verbatim}
+ C Basic Offset    ==> 2
+ C Default Style   ==> k\&r
+ C Offsets Alist   ==> X  statement-case-intro 1
+                       X  statement-case-open  1
+                       X  case-label           1
+\end{verbatim}
+
+Then in the same  \code{Customize Emacs} menu, choose
+\begin{verbatim}
+Settings Matching Regexp...
+\end{verbatim}
+then set the value of
+\begin{verbatim}
+ Comment Column    ==> 40
+\end{verbatim}
+
+If you want to use \code{//} style comments, see the top
+of the next section.
+
+\subsection{Setting variables directly via lisp hooks}
+\label{Lhooks}
+
+If you want to use \code{//} style comments, you may want to
+make \code{ESC;} insert them rather than the traditional
+\code{/* .. */} version.  If so, add something like this to
+your \file{.emacs} file:
+\begin{verbatim}
+(add-hook 'c-mode-hook
+          '(lambda ()
+             (setq comment-start "// ")
+             (setq comment-end "")))
+\end{verbatim}
+
+You can get fancier, of course. For example,
+\begin{verbatim}
+(setq ps-code t)                        ;this is Pan-STARRS code
+(add-hook 'c-mode-hook
+          '(lambda ()
+             (if (and (boundp 'ps-code) ps-code)
+                 (progn
+                   (setq comment-start "// ")
+                   (setq comment-end "")))))
+\end{verbatim}
+will make emacs use \code{//} if and only if the lisp variable
+\code{ps-code} is set and non-\code{nil}.
+
+To entirely bypass emacs' customize menus, also add this to your
+\textit{.emacs} file (I left the \code{ps-code} test in):
+\begin{verbatim}
+(add-hook 'c-mode-hook
+          '(lambda ()
+             (if (and (boundp 'ps-code) ps-code)
+                 (progn
+                   (setq c-basic-offset 2)
+                   (setq c-default-style '((other . "k&r")))
+                   (setq comment-column 40)
+                   (let ( el (vals
+                              '((statement-case-intro . 1)
+                                (statement-case-open . 1)
+                                (case-label . 1))) )
+                     (while vals
+                       (setq el (car vals))
+                       (setq vals (cdr vals))
+                       (setq c-offsets-alist
+                             (cons el
+                                   (assoc-delete-all
+                                    (car el) c-offsets-alist))))
+                     )
+                   ))))
+\end{verbatim}
+(and yes, there must be an easier way to set that alist. But this works).
+
+\bibliographystyle{plain}
+\bibliography{panstarrs}
+
+\end{document}
