%%% $Id: codeConventions.tex,v 1.18 2004-10-29 22:00:27 eugene Exp $
\documentclass[panstarrs]{panstarrs}

% basic document variables
\title{Pan-STARRS Image Processing Pipeline}
\subtitle{C Code Standards}
\shorttitle{C Code Standards}
\author{Robert Lupton}
\audience{Pan-STARRS PMO}
\group{Pan-STARRS Algorithm Group}
\project{Pan-STARRS Image Processing Pipeline}
\organization{Institute for Astronomy}
\version{01}
\docnumber{PSDC-430-004}

\begin{document}
\maketitle
\newcommand{\matchBracket}[1]{}         % help emacs match properly

% -- Revision History --
\RevisionsStart
% version     Date         Description
DR.00 & 2004/03/01 & First draft \\
00 & 2004/04/23 & First release \\
01 & 2004/10/28 & Title Changed \\
\RevisionsEnd

\textbf{\Large Referenced Documents}
\begin{center}
\begin{tabular}{|p{1in}|p{2.75in}|p{2.75in}|}
\hline
\textbf{\PS{} ID} & \textbf{Title} & \textbf{Author} \\
\hline
%%% References here.
\hline
\end{tabular}
\end{center}

\pagebreak
\tableofcontents

\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}


\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 explicitly permitted by the Sun Microsystems
copyright notice (Copyright.doc.html).

\subsection{To whom should I Complain?}

While we're working on this document complain to
\code{rhl@astro.princeton.edu}.

%------------------------------------------------------------------------------

\section{File Names}

This section lists commonly used file suffixes and names. 

\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} \\
Perl files & \code{.pl} \\
Python files & \code{.py} \\
\end{tabular}
\end{center}

\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.\\

\file{README} & 
The preferred name for the file that summarizes the contents of a
particular directory. \\

\file{TAGS} &
The index file (built by etags) used by emacs to follow cross references. \\
\end{tabular}
\end{center}


%------------------------------------------------------------------------------

\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 (\S\ref{SourceExample}).

\subsection{Source Files}

\subsubsection{Include Files}

Include files should have the following order:
\begin{itemize}
\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 
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 
Any \code{#define}d constants. {\bf Note:} \code{#define} should be used rather
than e.g. \code{const int}; C and C++ const semantics are different.

\item 
Any enums. 

\item 
Any typedefs and structs.

\item 
Any function prototypes.

\end{itemize}
e.g. for file \file{psThing.h}:
\begin{verbatim}
/** \file psThing.h
 * Support for psThings
 */

#if !defined(PS_THING_H)
#define PS_THING_H

#define PS_NMAX 10                        // maximum number of subthings

enum {PS_FIRST, PS_SECOND, PS_THRID};     // subthing sequences
typedef struct {
    int nthing;                           // number of subthings
    int sthing[PS_NMAX];                  // the subthings
} psThing;

/// make a new psThing
psThing *psThingAlloc(int nthing);

/// free an existing psThing
void psThingFree(psThing *thing);

#endif
\end{verbatim}
\tbd{add doxygen comments to this example}

\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}

\subsubsection{SWIG Interface Files}

\tbd{Write me}

%------------------------------------------------------------------------------

\section{Indentation}

Four spaces should be used as the unit of indentation.  Spaces are
recommended over tabs for indentation, but if tabs are used, the tabs
stops must be set to 8 spaces, not 4.

\subsection{Line Length}

Avoid lines longer than 110 characters.

When preparing documents, you should ensure that lines of this length
are not wrapped.  If you are using the standard PSDC \LaTeX{} class
file \file{panstarrs.cls}, \CODE|\begin{verbatim} ... \end{verbatim}|
will do this for you.

\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 or operator.

\begin{verbatim}
    if(a < b ||
       a > 2*b) {
	x = (a + b + c) +
	    sin(z);
    }
\end{verbatim}

\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\footnote{For emacs users, this means
the indentation that \code{<tab>} produces}.

\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.\footnote{This should be \emph{very} rare! Consider whether
you should be e.g. factoring code into a function.}

\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 4 spaces (note that putting the \code{anArg}
argument on a line of its own makes this the `natural' emacs indentation).

\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}

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}

%------------------------------------------------------------------------------

\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}

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.
 
\subsection{Implementation Comment Formats}

Programs can have four styles of implementation comments: block,
single-line, trailing, and end-of-line.

\subsubsection{Block Comments }
\label{ImplBlockComments} 

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.

See also Documentation Comments (\S\ref{DocComments}).

\subsubsection{Single-Line Comments}
\label{SingleLineComment} 

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 block comment format (\S\ref{ImplBlockComments}).

\subsubsection{Trailing Comments}
\label{col40} 

Very short comments can appear on the same line as the code they
describe, and should be indented to column 40\footnote{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}

\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 > 1) {

    // Do a double-flip.
    ...
} else {
    return false;          // Explain why here.
}
\end{verbatim}

\subsection{Documentation Comments}
\label{DocComments} 

Doxygen\footnote{{\tt  www.doxygen.org}}  will   be  used  to  produce
documentation of the types,  functions and variables without requiring
much  extra  effort  for   the  programmer.   Comments  starting  with
particular characters  (``tags'') are used by Doxygen  to identify the
relevant code to be documented.

Functions shall be tagged for Doxygenation by pre-pending them with a
block comment (\S\ref{ImplBlockComments}) which starts with a
\code{/**} instead of the usual \code{/*}.

Variables shall be tagged for Doxygenation by appending their
declaration with an end-of-line comment which starts with a
\code{///<} instead of the usual \code{//}.

An example of a function definition employing Doxygen-compatible
comments follows:

\begin{verbatim}
/** This is a really cool function.
 *  It does many really cool things.
 */
int reallyCoolFunction(int aNumber,     ///< This is a number 
                       float aRealNumber ///< This is a real number
                       )
{
    char *aString;                      ///< This is a string used to do stuff.

    /* Do really cool stuff */
    ...
}
\end{verbatim}

If you need to give information about a type, interface, or variable
that isn't appropriate for doxygenation, use a normal implementation
block comment (\S\ref{ImplBlockComments}) or single-line comment
(\S\ref{SingleLineComment}) immediately \textit{before} the code (as
exampled above). 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.

%------------------------------------------------------------------------------

\section{Declarations}

All globally-visible symbols must be declared in a suitable header
(.h) file.  Global private symbols should not appear in public header
files, but rather in separate, private header files.

\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, as per section~\ref{col40}).

\subsection{Initialization}

Try to initialize local variables where they're declared.  The only
reason not to initialize a variable where it's declared is if the
initial value depends on some computation occurring first.

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.

\subsection{Placement}

Variables should ordinarily be declared at the top of the block in
which they appear, unless there is some reason to declare them later.
This allows them to be initialised as they are created, and naturally
associates their declaration with their use.

For example, declarations are naturally mixed with assertions:
\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}

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 < maxLoops; i++) {
    ...
}
\end{verbatim}

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}

\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.  These comment blocks should
include doxygen-style comments to provide a brief desription as well
as other warnings, bugs, etc as needed.

\item The function's type should appear on the same line as the
function declaration.

\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, const char *descrip)
{
    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}

%------------------------------------------------------------------------------

\section{Statements}
\subsection{Simple Statements}

Each line should usually contain only one statement. Example:
\begin{verbatim}
x = sqrt(x2);                           // Correct
i++;                                    // Correct  
x = sqrt(x2); i++;                      // Avoid!
\end{verbatim}

An example of a reasonably two-statement line is:
\begin{verbatim}
argv++; argc--;
\end{verbatim}
where the two actions are intimately related.

\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}

\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}

\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}

\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 one of
the following forms:
\begin{verbatim}
for (initialization; condition; update);
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).

\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 one of the following forms:
\begin{verbatim}
while (condition);
while (condition) {}
\end{verbatim}

\subsection{do-while Statements}

A \code{do-while} statement should have the following form:
\begin{verbatim}
do {
    statements;
} while (condition);
\end{verbatim}

\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}

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.

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.

\subsection{label Statements}

Code labels should be indented to align with the previous level of
indentation.

%------------------------------------------------------------------------------

\section{White Space}
\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 Between logical sections inside a function to improve readability
\end{itemize}

\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
Binary operators should be separated from their operands by spaces.
Blank spaces should never separate unary operators such as a type
cast, unary minus, increment (\code{++}), and decrement (\code{--})
from their operands. Examples:
\begin{verbatim}
    a += c + d;
    a = (a + b) / (c * d);
    
    while (*d++ = *s++) {                 // Tricky way of copying until '\0'
        n++;
    }
    printf ("size is %d\n", foo);
\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 
The word \code{assert} should be treated as a keyword, and
separated by a space from its logical expression.
\end{itemize}

%------------------------------------------------------------------------------

\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.  Remember
these are guidelines for improving readability; clarity should trump
rigid adherence to the guideline.
 
{ \small 
\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.  Little words, such as 'for', 'to',
'at', etc, may be written in all lower-case or separated with
underscores if it makes the name clearer.

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 verbal phrases, in mixed case.

Namespaces should be protected by using special naming prefixes to
restrict the name space in particular libraries.  For example, the
PSLib functions are all prefixed with \code{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 

Variable names should not start with underscore \code{_} as these
names are, under some circumstances, reserved by the C
standard. Non-globally visible words should start with a lowercase
first letter; Internal words start with capital letters.

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;}\hfil\break
\code{char c;}\hfil\break
\code{float myWidth;}\hfil\break
\hfil\break
\code{int psNumOTA;}\hfil\break
\code{int p_psMyFiddleFactor;}\hfil\break

\\
 
Constants

&

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.

&
\code{#define PS_MAXLEN 40}\hfil\break
\CODE|enum { PS_ONE = 1, PS_TWO = 2 };|\hfil\break

\end{tabular}
}

%------------------------------------------------------------------------------

\section{Programming Practices}

\subsection{When to Make Symbols Global}

Declare all functions and top-level variables \code{static} within a
file if they are not needed outside of the file.  {\bf Note:} do not
confuse this use of \code{static} with its usage to make
auto-variables within a function persistent.

A name (whether of a variable, a function, or a type) shall start
\code{ps} (or \code{p_ps}) if and only if it is visible at global
scope.  The distinction is that \code{p_ps} names are not part of the
documented APIs, but need to be exposed for some reason.

\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.  

\subsection{Type Qualifiers (const and restrict)}

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{{\bf Note:} compilers are free to ignore the \code{restrict}
keyword, so all code should be written to explicitly handle aliasing}.

\subsection{structs and typedefs}

All structs should be defined as \code{typedef}s.

A struct should not include a struct
tag unless it's self-referential; E.g.
\begin{verbatim}
typedef struct myStruct { 		// Omit "myStruct"
    int x;
} myStruct;

typedef struct yourStruct { 		// OK
    struct yourStruct *next;
    int x;
} yourStruct;
\end{verbatim}

\subsection{Variable Assignments}

Avoid assigning several variables to the same value in a single
statement, unless the variables are intimately related. Acceptable examples:

\begin{verbatim}
row0 = col0 = 0;
sum = sumx = sumy = 0;
\end{verbatim}

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}

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}

\subsection{Miscellaneous Practices}
\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. In cases where the precedence rules
are clear, the parentheses may be omitted.

\begin{verbatim}
if (a & b || c & d)                     // AVOID!
if ((a & b) || (c & d))                 // RIGHT
\end{verbatim}

There are some famous problems with precedence in C.  In particular,
expressions involving the combinations of \code{||} and
\code{&&} should be fully 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}

\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}

\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 >= 0) ? x : -x;
\end{verbatim}

\subsubsection{Functions that Take No Parameters}

When a function takes no arguments, it should be explicitly declared
as \code{void}:
\begin{verbatim}
static type myFunction(void)
{
    ...
}
\end{verbatim}


\subsubsection{Special Comments}

Doxygen has special comments which are used to provide specific notes
in the code.  These are added in as special entries and sections in
the Doxygen-generated documentation.  These special comments should be
used in addition to the Doxygen usage to make these types of
conditions easily searchable.

\begin{itemize}
\item 
Use \code{\warning} in a comment to flag something that is bogus but works.

\item 
Use \code{\bug} to flag something that is bogus and broken.

\item 
Use \code{\todo} to note additional work to be done 

\item 
Use \code{\note} to make other general notes 

\item 
Use \code{\test} to list test cases 

\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}
\end{itemize}

%------------------------------------------------------------------------------
\appendix				%Begin Appendices
%------------------------------------------------------------------------------

\section{Code Examples}
\subsection{Source File Example}
\label{SourceExample} 

\tbd{Need to include more of the rules, and shorten the example}
Here's \file{psBuffer.h}:
\begin{verbatim}
#if !defined(PS_BUFFER_H)               /* here's the insides of psBuffer.h */
#define PS_BUFFER_H
#define PS_BUFSIZE 128                  // Size for I/O buffers

typedef struct {
    char buf[PS_BUFSIZE];               // buffer
    int n;                              // number of bytes in buffer
} psBuffer;

psBuffer *psBufferAlloc(void);
void psBufferFree(psBuffer *buf,         // buffer to delete
                 int deep);             // NOTUSED. Do a deep delete

void psBufferAppend(psBuffer *restrict buf, // psBuffer to append to
                    const char *restrict str); // string to add

#endif
\end{verbatim}

And here's the C source; \file{psUtils.h} provides \code{psAlloc/psFree}.

\begin{verbatim}
/*
 * This file implements an example of formatting a file of C code
 *
 * 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"
#include "psBuffer.h"

typedef enum { CRNL, NL } NLType;

static char *getNewline(NLType type);   // return a suitable newline

static psBuffer *buf = NULL;            // I/O buffer

/*****************************************************************************/
/*
 * Create/destroy psBuffers
 */
psBuffer *psBufferAlloc(void)
{
    psBuffer *buf = psAlloc(sizeof(psBuffer));
    buf->n = 0;

    return buf;
}

void psBufferFree(psBuffer *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 psBuffer
 */
void psBufferAppend(psBuffer *restrict buf, // psBuffer to append to
                    const char *restrict str) // string to add
{
    assert(str != NULL);
    const int len = strlen(str);

    if (buf->n + len >= PS_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 = psBufferAlloc();
    long t;                               // current time

    while(t = (long)time(NULL), t%3 == 2) {}
    
    if (t%3 == 0) {
        psBufferAppend(buf, "Hello");
    } else if (t%3 == 1) {
        psBufferAppend(buf, "Aloha");
    }
    psBufferAppend(buf, " World!");

    psBufferAppend(buf, getNewline(NL));

    psBufferFree(buf, 0);

    return 0;
}

/*****************************************************************************/
/*
 * Return a desired line terminator
 */
static char *getNewline(NLType type)    // what sort of newline?
{
    char *newline;                      // newline to add
    switch (type) {
      case CRNL:
        newline = "\r\n";
        break;

      case NL:
        newline = "\n";
        break;

      default:
        newline = "NL";                     // FIXME
        break;
    }

    return newline;
}
\end{verbatim}

%------------------------------------------------------------------------------

\section{Departures from Sun Java Coding Standards}

Apart from changes required by our use of C99 rather than Java,
this document differs from the original Sun-Java standard in
two sorts of ways; additions and changes.

\subsection{ Additions to the Sun-Java standards}

\begin{itemize}
\item
    Naming convention for include files

\item
  Added naming conventions for constructors, destructors, and conversion
  functions.

\item
  Specified that the `output' argument should come \emph{first}.

\item
  Added conventional comments for unused arguments and unreachable
  statements (conforming to Doxygen's conventions).

\item
  Specified that functions taking no arguments should be explicitly
  specified as \code{(void)} (avoiding complaints on some compilers,
  e.g. on SGIs).

\item
  Added rules on typedefing structs, and on struct tags.

\end{itemize}

\subsection{Departures from the Sun-Java standards}

\begin{itemize}

\item
  We break lines \emph{after} (not before) an operator.

\item
  We don't specify any special indentation for continued logical
  expressions within an \code{if} clause.

\item
  Specify that \code{case/break} statements should be indented
  by half an indent (2 spaces)

\item
  Comments need not be preceeded by a blank line

\item
  The restriction on only declaring variables at the top of blocks (including
  \code{for} loops has been somewhat relaxed.

\item
  Relaxed the `only one statement per line' rule a little.

\item
  High-precedence binary operators (\code{*}, \code{/}, \code{%} and above)
    should \emph{not} be surrounded by whitespace.

\item
  The line-length limit has been changed from 80 to 110 characters.

\item
  Relaxed wording to allow parentheses to be omitted when the precedence
  is well known and unambiguous.

\end{itemize}

%------------------------------------------------------------------------------

\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.}

The easiest way to use these conventions while writing code using
emacs is to get \file{panstarrs.el} from \code{cvs} with the command
\begin{verbatim}
  cvs -d poiserver0.ifa.hawaii.edu:/usr/local/cvs/repositories/pan-starrs co Templates
\end{verbatim}
and then grab \file{Templates/panstarrs.el}.  Then add:

\begin{verbatim}
(load-file "/home/you/Templates/panstarrs.el")
(add-to-list 'auto-mode-alist (cons "\\.[ch]$" 'panstarrs-c-mode))
\end{verbatim}                          % $ % match that $ for emacs
to your \file{.emacs} file; this will use \code{panstarrs-c-mode}
for all \file{.c} and \file{.h} files.

If you want to
\begin{itemize}
  \item use C99-style comments (i.e. \code{//} to end of line)
  \item have your emacs window set to 110 characters wide
  \item somewhat improve (or spoil?) the handling of re-indenting comments
\end{itemize}
add one or more of these \code{add-hook} commands to your \file{.emacs} file too:
\begin{verbatim}
(add-hook 'panstarrs-c-mode-hook 'panstarrs-c99-comments)
(add-hook 'panstarrs-c-mode-hook 'panstarrs-set-width)
(add-hook 'panstarrs-c-mode-hook
	  '(lambda ()
	     (set (make-variable-buffer-local 'comment-indent-function)
		  'panstarrs-comment-indent)))
\end{verbatim}
          
\section{How to Achieve This Style with Astyle}
\label{astyle}

The purpose of a coding standard is to improve coding efficiency, not
to hinder it.  Since people are inherently falible, 100\% adherence to
the standard is an impossible goal for human-generated code.
Furthermore, laziness and slopiness are human nature.  To minimize the
amount of effort spent in keeping software in line with a coding
standard is to use automatic re-formatting tools to enforce the
standard.  Various software tools exist to perform these tasks.  One
of these is \code{astyle}, an open-source tool which takes a variety
of options which allow the use to tailor the coding standard to suit
their preferences.  We have determined the following collection of
astyle options which achieve the many of the coding standard
guidelines specified above.  Note that any of the listed options
(always in the 'long' form) may be specified in the user's
\code{.astylerc} file by dropping the leading dash.

\begin{itemize}
\item \code{--mode=c} - This option tells \code{astyle} to recognize
  the source code as C code.

\item \code{--indent-switches} - This option tells \code{astyle} to
  indent the \code{case} statements in a \code{switch}.  Do not also
  specify \code{--indent-cases}.

\item \code{--indent-labels} - This option tells \code{astyle} to add
  indentation to labels so they are indented one level less than the
  current level.

\item \code{--min-conditional-indent=0} - This option tells
  \code{astyle} not to add indentation to successive lines of
  multiple-line conditional statements.

\item \code{--max-instatement-indent=20} - This option tells
  \code{astyle} to limit the total amount of indentation to 20 spaces.

\item \code{--pad=oper} - This option tells \code{astyle} to add
  padding about binary operators.

\item \code{--brackets=break} - This option tells \code{astyle} to
  break brackets from their pre-block statements, dropping them to the
  next line.

\item \code{--convert-tabs} - This option tells \code{astyle} to
  convert tabs into the equivalent number of space characters.

\item \code{--indent=spaces=4} - This option tells \code{astyle} to
  use 4 spaces per indent level.
\end{itemize}

\bibliographystyle{plain}
\bibliography{panstarrs}

\end{document}
