The sort subroutines consist of a set of packages. Most of the lower
level packages can be run independently, but the higher level ones force
you to use the lower level ones.

Known bugs
==========

adc number > 384 taken as TDC is hard coded in 1 or 2 places.
input_adcvals is broken.
detprocs is tied to specifically to the types of experiment Steve C has been
doing.

To do
=====

Find an way of distinguising routines that have to be seen by other routines
in a package from those that have to be seen by the user. 

List of packages
================

Here is a quick list of packages, what they do, and what they rely on. If
a packages is marked as relying on Sunsort then it can only be used from
sort codes, otherwise, it could be used from stand-alone programs.

FORTRAN calling sequences are described here in a similar way to ANSI-C
prototypes. Hopfeully it should be obvious what is meant.

Package: Utility
----------------

Relies on: Sunsort
C include file: hitsubs.h
FORTRAN include files: hitsubs.i

This packages contains useful standard routines to help with checking
data. The routines only look at the raw ADC lists, and are consequently
safe for use with any sort code.

Routine:     void chann_dump(int dumpflag, int maxchans)
	     subroutine chann_dump(integer dumpflag, integer maxchans)
Description: This routine examines the first maxchans ADC channels, and,
	     depending on the value of dumpflags, increments maxchans+2
	     1d spectra (they must be defined in the sort code), or dumps
	     the event to the terminal, or both. Return value is meaningless
	     at the moment.

	     set dumpflags to DUMP_ONLY to write the event to the terminal
	     set dumpflags to SPEC_ONLY to increment the spectra
	     set dumpflags to DUMP_N_SPEC to do both

	     ADC(1) goes into spectrum 1, ADC(2) into spectrum 2 etc.
	     Spectrum maxchans+1 holds a summary of how many non-zero
	     hits were in each channel.
	     Spectrum maxchans+2 holds a summary of how many zero hits
	     were in each channel

Routine:     void adclist_dump()
	     subroutine adclist_dump
Description: This routine writes both the adclist array and the elements
	     of the adc array which are >= to 0 to the terminal. This is
	     useful for checking that your code is reading the adclist
	     and/or the adc array correctly.

Routine:     void input_adcvals()
Description: This routine provides a way of entering ADC values from the
	     keyboard diretly into the sort code. This is useful for testing
	     sort codes.
To do:	     Fix it, looking at it, I think it's broken.
	     Add FORTRAN compatability routine.

Routine:     void plot_hits(int sp1_channsat, int sp1_zeroat, int sp2_ahit,
		 int sp2_thit)
	     subroutine plot_hits(integer sp1_channsat, integer sp1_zeroat,
	         integer sp2_ahit, integer sp2_thit)
Description: Generate 1d channel hit and zero hit plots showing which ADC
	     channels are being hit and which are getting zeroes, and also
	     generate 2d 'tartan' plot showing which ADCs fired with which
	     other ADCs. sp1_channsat is the number of the 1d spectrum to
	     hold the non-zero hit spectrum, sp1_zeroat is the number of
	     the 1d spectrum to hold the zero hit spectrum, sp2_ahit and
	     sp2_thit hold the numbers of the 2d spectra to hold ADC and
	     TDC hits.
To do:	     Allow spectrum numbers of 0 to be passed to indicate that
	     that spectrum shouldn't be generated.
	     Find a more flexible way of specifying which ADCs go into
	     sp2_ahit and which into sp2_thit. The current criterion (> 384)
	     is specific to the ANU DA system and assumes you have a
	     particular mapping file. Also, you may want to see correlations
	     between ADCs and TDCs.

Package: Structure
------------------

Relies on: Sunsort
C include file: hitsubs.h
FORTRAN include file: hitsubs.i

This package provides a way of storing the structure of the experiment that is
accessible to the code. This allows general routines to be written which don't
need to know the structure of a specific experiment, instead they can pick
their information out of here.

The structure is held as a tree starting with the topmost element which is
called "experiment". It's up to the user to decide how to sub-divide the
experiment into detectors. A simple division may be to say that an experiment
consists of 2 psssds and 2 monitors. Each psssd consists of 16 strips. Each
strip consists of signala, signalat, signalb and signalbt. Each monitor
consists of signala and signalat. This would lead to a tree like: 

        			   experiment
        			 ,'   /   \  `.
        		       ,'    /     \   `.
        		     ,'     /       \    `.
        	           ,'      /         \     `.
                         ,'       /           \      `.
                     pssd      pssd         monitor    monitor
               ,::'///|||\\\`::.  :          /   \        :
             strip x 16 ......... :     signale signalet  :
           .' / \ `.
         .'  /   \  `.
       .'   /     \   `.
     .'    /       \    `.
signala signalat signalb signalbt
        
Typically an extra detector will be modelled called 'junk' which will
contain all the unused ADCs to allow then to be seen from the experiment
structure.

Each level of the tree is handled in the same way. It is described by a
variable of type struct detectors. In C you can traverse the tree by
manipulating pointers. In FORTRAN routines are provided to access the tree,
these routines keep track of where you are.

The package structure provides many variables that are attached at each level
of the structure. Some of these are used by other packages. See the relavent
package description for more details. If you are using those packages then you
should use the variables as described (or more likely leave them to the
package to manage). If you are not using the package then leave those variables
alone as they are subject to change.

Type:        struct detectors {
	         struct detectors *parent;
		 struct detectors *children;
		 struct detectors *next;
		 struct information *info;
		 int number;
		 short adcnum;
		 short hits;
		 struct {
		     struct detectors *head;
		     struct detectors *next;
		 } hitlist;
		 double gain;
		 double offset;
		 int threshmin;
		 int threshmax;
		 double value;
		 void *user;
	     };

This structure holds the information about each node in the structure tree.
The entries have the following meanings:

    parent:	 points up the tree to the node to which this node is attached.
		 It is NULL for the node 'experiment'.
    children:	 points down the tree to the first node that is attached
		 below this node. It is NULL for a leaf node.
    next:	 points across the tree to the next node at the same level,
		 that is the next node with the same parent. It is NULL for
		 the last node on a level.
    info:	 points to some more information about this node.
    number:	 The number of this node at this level. The first node at this
		 level is numbered 1. In the example above, on the level below
		 experiment, the pssds will have numbers 1 and 2, and the
		 monitors numbers 3 and 4. The numbers will match the order of
		 children and next, that is, children always points to a node
		 with number 1 and next always points to the node with the
		 number one higher than the current node.
    adcnum, hits, hitlist, gain, offset, threshmin, threshmax and value:
	         These are provided for the use of other packages.
    user:	 A hook on which you can place your own data. This hook is
		 initialised to NULL. If the event structure is destroyed
		 (which happens whenever it is reinitialised) and if this
		 pointer is non-NULL then it is freed by calling free().

Type:	     struct info {
	         char *name;
		 int ndetel;
		 ...		    /* The rest of this structure is opaque */
             };

This structure holds some information which is the same for all nodes of the
same type (for example all pssd nodes have info pointers which point to
the same structure). Most of the entries in this structure are for the
internal use of the sort subroutines, so leave them alone. The following are
available to be read and under no circumstances must they be written to:

    name:    A string holding the name of the type of this node
    ndetel:  Subject to change, will be documented later

As far as the structure package is concerned, the only node type name with
any special meaning is 'experiment'. When the structure is loaded from file,
the package expects to find exactly one node called 'experiment' it will
make this the top node in the structure tree.

FORTRAN routines only have access to one experiment tree. C routines can
load multiple trees if they desire. C routines have to pass the head of
the tree to most routines to show which tree they want to access. An external
variable:

	struct detectors *expt;

is provided which the FORTRAN routines always use. Users who wish to access
the same tree from C and FORTRAN should set this variable.

Routine:     struct detectors *loadexperiment(char *filename)
Description: Loads the experiment structure from file. It returns a pointer
	     to the top level of the experiment structure, that is to a node
	     called experiment. The file structure is documented elsewhere.

	     To automatically set the FORTRAN pointers, either do:

		expt = detector_ = loadexperiment(filename);

	     or:

		loadexperiment_(filename);

	     and access the variable expt to get the pointer to the head
	     of the tree.

Routine:     int setdetprocs(char *name, int (*preinit)(struct detectors *),
                 int (*init)(struct detectors *),
                 int (*preevent)(int, struct detectors *),
                 int (*event)(int, struct detectors *))
	     integer function setdetprocs(character*(*) name,
		 integer function preinit(),
                 integer function init(),
		 integer function preevent(integer),
		 integer funciton event(integer))
Description: This routine defines which routines are to be called to
	     initialise and to process an event for each node in the structure.
	     Name is the name of the structure as given in the experiment
	     file. Preinit, init, preevent and event are the four functions
	     to be called at various times. See the section Detector Routines
	     later for more details.

	     These function can only be used if all detector procedures
	     are of the same type (C or FORTRAN) to set mixed types, you
	     must use the setdetprocsmixed() call from C.

Routine:     int setdetprocsmixed(char *name, void *preinit, int preinit_type,
	         void *init, int init_type, void *preevent, int preevent_type,
		 void *event, int event_type)
Description: This routine behaves as setdetprocs but the type of each routine
	     can be specified. Use DETPROC_F to specify a FORTRAN routine,
	     and DETPROC_C to specify a C routines. Fortran routines should
	     be declared with lines like:

	         int mydetector_preinit_(void);
	         int mydetector_init_(void);
	         int mydetector_preevent_(int *);
	         int mydetector_event_(int *);

	     Function pointers should then be cast to void * in the call.

Routine:     void expt_dump(struct detectors *dp, int indent)
	     subroutine expt_dump(integer indent)
Description: Writes a textual description of the experiment tree to stderr. It
	     also dumps the values of the variables used in other packages in
	     brackets so ignore them if you aren't using them.

	     In C you may pass it a pointer to the node from which you want
	     to dump the tree this allows you to dump part of the tree. In
	     FORTRAN the only option is to dump the whole of the default
	     tree.

	     The parameter indent controls how many spaces are put at the
	     start of a line, it is incremented by 4 for each level down the
	     tree.

Routine:     int detector_init(struct detectors *dp)
	     integer function detector_init()
Description: Perform user specified initialisation for all elements in the
	     experiment tree for which intialisation routines were specified
	     with setdetprocs(). See the section Detector Routines later for
	     more details. The return value is that of the last detector
	     routine that was called.

	     In C pass this routine the pointer to the top of the experimental
	     tree. In FORTRAN this always processes the default tree.

Routine:     initprops
Description: Ignore, this is for internal use only
To do:	     Hide it

FORTRAN routines:

There are many subroutines for accessing the experiment tree from FORTRAN.
The routines keep track of a current position in the tree. Routines are
provided to move this position around the tree. Routines are provided to
access data at this position, and to access data at an arbitrary position.
In general, it's faster to access the data at the current position.

Loading routines:

integer loadexperiment(character*(*) filename)
	This routine loads an experiment in the same way as the C function
	loadexperiment() does. However, it also initialises the FORTRAN
	compatability routines. They will not work if this routine is not
	called, hence, if you want to mix C and FORTRAN, you must load the
	experiment structure through the FORTRAN call. In C this can be done
	by calling loadexperiment_(char *filename). The pointer to the top
	level of the experiment tree can be found in the external variable
	experiment_. This routine returns 1 for success and 0 for failure.

Movement routines:

subroutine detectortop:
    Move to the top of the experiment tree.
integer function detectorparent():
    Move to the parent of the current position (*).
integer function detectornext():
    Move to the next node on the same level (*)
integer function detectorchildren():
    Move to the first node at the next level. (*)
integer function detectorsave():
    Remember the current position (returns 0 if it works, 1 if out of memory).
integer function detectorrestore():
    Return to the last saved position (returns 0 if it works, 1 if no more
    saved positions).
subroutine detectorforget():
    Forget all saved positions.

* Returns 0 if move was successful, non-zero if there was nowhere to go (that
  is, it was at the top, right, or bottom of the tree).

Data retrieval routines:

Each of these routines is available in 2 flavours. For a variable called xxx
there's a routine getthisxxx() which gets the data for the current node, and a
routine getxxx(reference, ...) which gets the data for a node given an
absolute reference from experiment without moving the current pointer. A
reference is of the form:

	  node.node.node.node...

where node is either the name of the node, or the character '%' to indicate
that the next parameter should be read to indicate how many steps along the
three to take. For example, signalbt of the thirds strip of the second
pssd in the example tree above can be referenced as:

     ('%.%.%',2,3,4)

or

    ('%.%.signalbt',2,3)

Naturally, only nodes with unique names at a level should be reference by
name, others should be referenced by number.

The following routines are available for accessing constant information
about a node.
      
character*80 function getname(...), getthisname():
    Returns the name of the detector type at this node.
integer function getnumber(...), getthisnumber():  
    Returns the number of the node.
integer function getndetel(...), getthisndetel():
    Returns the number of children (sub-elements) this node has.

Package: ADCs
-------------

Relies on: Structure Sunsort
C include file: hitsubs.h
FORTRAN include file: hitsubs.i

This package uses the variable adcnum in the struct detectors type provided
by the package Structure. It activates it to mean the adc associated with
that node in the tree. It is initialised to -1.

Routine:     int loadadcs(struct detector *dp, char *filename, int tdcoffset)
	     integer function (character*(*) filename, integer tdcoffset)
Description: This routine loads the adc values from the specified file into
	     the structure. Only nodes whose names begin with 'signal' are
	     considered candidates for loading. If tdcoffset is set to zero
	     then the routine expects every signal to have a number in the
	     file. If tdcoffset is non-zero then only every other signal
	     is read from the file, the others are set to the last value read
	     plus tdcoffset. This routine expects there to be at least as many
	     numbers in the file as nodes called 'signal...'. It returns 0 for
	     a successful load, and non-zero for an error.

	     In the input file, anything from a '!', '#' or '*' to the end
	     of a line is ignored.

	     In the C routine, dp should point to the top of the tree that
	     you wish to load. You may load part of a tree by specifying a
	     pointer partway down the tree. In FORTRAN this routine always
	     loads the whole of the default tree.

FORTRAN only routines:

Routines:    integer function getadcnum(...), getthisadcnum()
Description: Return the adcnum for the specified node, the specification is
	     the same as that described for the get routines in package
	     Structure.

Routines:    subroutine setadcnum(integer value, ...)
	     subroutine setthisadcnum(integer value)
Description: Set the adcnum variable for a node. The specification is the
	     same as in the get routines, however, note that in setadcnum
	     the value comes before the reference (for example, call
	     setadcnum(67,'%.%.signalbt',2,3) would set adcnum in the node
	     given above as an example reference to 67).

Package: Markhits
-----------------

Relies on: ADCs Structure Sunsort
C include file: hitsubs.h
FORTRAN include file: hitsubs.i

This package provides a fast way to identify which parts of a large detector
system have been involved in an event. This, coupled with the almost object
orientated approach of the Structure package, provides a very flexible and
sophisticated approach to processing events. The clever way in which it is
coded avoids many of the overheads associated with traditional sorting
approaches, consequently it can be faster than a standard sort code
(particularly when the event processing is simple so standard sort codes spend
most of their time finding which detector elements have fired).

This package activates the following variables in struct detectors:

     hits:         The number of children of this node that were hit in an
		   event
     hitlist.head: a pointer to the first child of this node that was hit.
     hitlist.next: a pointer to the next node at this level that was hit
     gain:	   multiplicative factor for gain correction
     offset:	   offset for gain correction
     threshmin:	   The lowest raw adc value that will be caounted as a hit
     threshmax:	   The highest raw adc value that will be counted as a hit
     value:	   The adc reading after correction with gain and offset

gain, offset, threshmin and thresmax may be read and written. value may
also be read and written, but it's usually treated as read only as its
contents are reset for each event. hits and hitlist must never be written to.

When an event is processed with this package, it first finds which ADCs have
been hit, it propigates the hits up the tree so that at each level, the hit
variable holds the number of immediate sub-elements that were hit. For
example, if in an event in the example experiment structure given above caused
signala, signalat, signalb and signalbt of the first pssd to be hit, and
signale and signalet of the second monitor to be hit, then those elements
would have hit set to one and all other signal elements would have hit set to
zero. The first pssd would have hit set to four, the second pssd would have
hit set to zero, the first monitor would have hit set to zero and the second
monitor would have hit set to two. At the top level, experiment would have hit
set to two.

The members of hitlist could be used to traverse the experiment structure to
find just the elements that have been hit and to process them, but in
practice, it's much easier to use the detector_event() call which does all the
hard work for you and then calls the right routine for the detector type
that's been hit. The key to getting fast processing is to get this detector
processing working properly. See the section Detector Routines later for more
details.

Routine:     int initmarkhits(struct detectors *dp, int nadcs)
	     integer function initmarkhits(integer nadcs)
Description: This routine initialises the markhits package for use. It must
	     be called before markhits() or markhitslist() is called.

	     On entry to the C routine, dp should point to the top of the
	     experiment tree. The FORTRAN routine always refers to the top of
	     the default experiment tree.

	     On entry nadcs should hold the highest ADC number used in the
	     experiment.

	     Returns 0 on success and <0 on failure.

Routine:     void markhits(short *adc)
	     subroutine markhits(integer*2 adc(*))
Description: This routine marks the experiment tree with which elements have
	     been hit. It then propigates the hits up the tree so that every
	     element has the correct hits value. adc should be the adc array
	     that was passed to the sort code. This call is deprecated, it's
	     much faster to call markhitslist.

Routine:     void markhitslist(short *adclist, short *adc)
	     subroutine markhitslist(integer*2 adclist(*), integer*2 adc(*))
Description: This routine does the same thing as markhits only faster. Adclist
	     and adc should be the list of which adcs have fired, and their
	     values as passed to the sort code.

Routine:     int loadgainoffset(char *filename)
	     integer function loadgainoffset(character*(*) filename)
Description: Load the gains and offsets from the file specified in filename.
	     The file should consist of a series of lines of the form:
		 adc gain offset
	     where adc is the adc number (integer) and gain and offset are
	     the (real) gain and offset to use for that adc. Lines in the
	     file that start with # or that are blank are ignored. This call
	     returns 0 if all went well, 1 if there was an error. If this
	     call isn't made, or if the file couldn't be found then the gains
	     and offsets will default to 1.0 and 0.0 respectively. Similarly,
	     any adcs not mentioned in the file will have their gains and
	     offsets default to 1.0 and 0.0.

Routine:     int loadthresholds(char *filename)
	     integer function loadthresholds(character*(*) filename)
Description: Similar to loadgainoffsets excepts it loads the thresholds from
	     file. The file format is
		   adc min max
	     The defaults values for min and max are 1 and something slightly
	     over 250,000,000 respectively. If you feel that hits which give
	     a reading of zero are important and should be processed, then you
	     should set the minimum threshold to 0.

Routine:     int detector_event(int proc, struct detectors *dp)
	     integer function detector_event(integer proc)
Description: Process an event by calling the event handling routines set with
	     setdetprocs. Only those elements that were hit in this event are
	     called. Proc is an integer that is passed to the detector
	     routines to allow you to chose what processing is done. See
	     the section Detector Routines later for more details. The return
	     value is that of the last detector routine that was called.

	     The C routine should pass the top of the experiment tree in dp.
	     The FORTRAM routine always refers to the top of the default
	     experiment tree.

Routine:     void event_dump(struct detectors *dp, int indent)
	     subroutine event_dump(integer indent)
Description: Dumps out which bits of the event structure have been hit and
	     the value of hits. Also, for those elements which have adcs
	     associated with them (that is, have had their adcnum set to
	     something other than -1), it dumps the adc number, the raw
	     value and the processed value.

	     You can pass a pointer to the top of a sub-tree in the C routine
	     to just dump out part of an experiment. The FORTRAN routine
	     always dumps out the whole experiment.

Routine:     void plot_chanspecs(int plot_type, struct detectors *dp,
	         int sp2_channsa, int sp2_channst)
	     subroutine plot_chanspecs(integer plot_type, integer sp2_channsa,
	         integer sp2_channst)
Description: Routine to generate some standard spectra very quickly.

	     sp2_channsa and sp2_channst hold the numbers of the 2d spectra
	     used for the plots of energy like signals and time like signals
	     respectively.

	     On entry, plot_type should be set equal to one of the following
	     symbols to get the listed effect.

	     PLOT_2D
	         Plot raw adcvalues as a function of channel number into the
		 2d spectra.
	     PLOT_2DC
	         Plot the calibrated values as a function of channel number
		 into the 2d spectra.
	     PLOT_A
	         Plot the raw energy like signals into 1d spectra with channel
		 1 in spectrum 1 etc. Also do PLOT_2D as well.
	     PLOT_T
	         Plot the raw time like signals into 1d spectra with the time
		 corresponding to energy channel 1 in spectrum 1 etc. Also do
		 PLOT_2D as well.
	     PLOT_AT
	         Equivalent to PLOT_A and PLOT_T with both energy and time
		 going on the same spectrum. Both are divided by 2 and
		 the time has 4096 added to push it to the top of the spectrum.
		 Also do PLOT_2D as well.
	     PLOT_AC
	         As PLOT_A but with calibrated values (so 2d plot is equivalent
		 to PLOT_2DC).
	     PLOT_TC
	         As PLOT_A but with calibrated values (so 2d plot is equivalent
		 to PLOT_2DC).
	     PLOT_ATC
	         As PLOT_A but with calibrated values (so 2d plot is equivalent
		 to PLOT_2DC).

To do:	     Find a more flexible way of specifying which channels are ADCs
	     and which are TDCs.

FORTRAN only routines:

The following get and set routines are provided for use in FORTRAN codes.
Their syntax is the same as similar routines provided in the ADCs and
Structure packages.

double precision function getgain(...)
double precision getthisgain()
subroutine setgain(double precision value, ...)
subroutine setthisgain(double precision value)
double precision function getoffset(...)
double precision getthisoffset()
subroutine setoffset(double precision value, ...)
subroutine setthisoffset(double precision value)
integer function getthreshmin(...)
integer getthisthreshmin()
subroutine setthreshmin(integer value, ...)
subroutine setthisthreshmin(integer value)
integer function getthreshmax(...)
integer getthisthreshmax()
subroutine setthreshmax(integer value, ...)
subroutine setthisthreshmax(integer value)
double precision function getvalue(...)
double precision getthisvalue()
subroutine setvalue(double precision value, ...)
subroutine setthisvalue(double precision value)

integer function detectorhitlistnext()
	Move to next hit element at this level
integer function detectorhitlisthead()
	Move to first hit element at next level

Package: Vector
---------------

Relies on: Nothing
C include file: vector.h
FORTRAN include file: n/a

The package may not be accessed directly from FORTRAN.

This package allows the user to manipulate a vector object in a variety of
ways. Evaluations of expensive functions are delayed until the result is
requested and then cached to save re-evaluation.

The vector structure is opaque and should not be accessed directly by the
user, all accesses should go through wrapper functions and macros.

To declare a new vector, do:

   struct vector vec;

The following parameters may be read from a vector:

x   The X component
y   The Y component
z   The Z component
r   The length of the vector
r2  The length of the vector squared
t   Spherical polar theta in radians
td  Spherical polar theta in degrees
p   Spherical polar phi in radians
pd  Spherical polar phi in degrees
tx  Rectangular polar theta-x in radians
txd Rectangular polar theta-x in degrees
ty  Rectangular polar theta-y in radians
tyd Rectangular polar theta-y in degrees

All parameters are double precision floating point numbers.

For each parameter `par' from the above list, there are two corresponding
functions to read the parameter: vector_par and vector_par_safe. Each function
takes 1 argument - a pointer to a structure vector. Normally vector_par should
be used. Where possible this will be implemented as a macro for added
speed. All macros are written to behave correctly inside expressions and after
control structures like if and while - no extra braces are needed above what
one would expect for a function call. If the macro is not suitable in a
particular circumstance, then use the function call. In particular note that
the macro versions may evaluate their parameter more than once so constructs
like:

    px = vector_x(v++);

should be avoided, either rewrite it as:

    px = vector_x(v);
    v++;

or use the safe version:

    px = vector_x_safe(v++);

To set a vector, the following functions are provided. Each of them expects
to be passed a pointer to the vector to be set, and returns the same pointer.

Routine:     struct vector *vector_set_xyz(struct vector *v, double x,
	     double y, double z)
Description: Sets vector v from an x, y and z triplet.
Routine:     struct vector *vector_set_rtp(struct vector *v, double r,
	     double theta, double phi)
Description: Sets vector v from an r, theta, phi spherical polar triplet.
	     theta and phi should be in radians.
Routine:     struct vector *vector_set_rtpd(struct vector *v, double r,
	     double theta, double phi)
Description: Sets vector v from an r, theta, phi spherical polar triplet.
	     theta and phi should be in degrees.
Routine:     struct vector *vector_set_rtt(struct vector *v, double r,
	     double thetax, double thetay)
Description: Sets vector v from an r, thetax, thetay rectangular polar triplet.
	     thetax and thetay should be in radians.
Routine:     struct vector *vector_set_rttd(struct vector *v, double r,
	     double thetax, double thetay)
Description: Sets vector v from an r, thetax, thetay rectangular polar triplet.
	     thetax and thetay should be in degrees.

The following manipulation routines are provided:

Routine:     struct vector *vector_scale(struct vector * v, double scale)
Description: Multiplies the length of vector v by scale, returns v.
Routine:     struct vector *vector_normalise(struct vector *v)
Description: Normalises vector v, returns v.
Routine:     struct vector *vector_scale_to(struct vector *v, double length)
Description: Sets the length of vector v to length, returns v.
Routine:     struct vector *vector_scale_to2(struct vector *v, double length2)
Description: Sets the length of vector v to sqrt(length), returns v. The
	     calculation of the sqrt is delayed as long as possible so if you
	     happen to calculate a new value of |v|^2 use this routine rather
	     than taking the square root and calling vector_scale_to.
Routine:     struct vector *vector_copy(struct vector *d, struct vector *s)
Description: Copies vector s into vector d. Returns d.
Routine:     struct vector *vector_add(struct vector *a, struct vector *b,
	     struct vector *c)
Description: Sets vector a to be the sum of vectors b and c. Returns a.
Routine:     struct vector *vector_sub(struct vector *a, struct vector *b,
	     struct vector *c)
Description: Sets vector a to be the vector difference b-c. Returns a.
Routine:     double vector_dot(struct vector *a, struct vector *b)
Description: Calculates the dot product of a and b.
Routine:     struct vector *vector_cross(struct vector *a, struct vector *b,
	     struct vector *c)
Description: Sets vector a to be bxc. Returns a.


Package: Coord
--------------

Relies on: Vector
C include file: evsubs.h
FORTRAN include file: n/a

The package may not be accessed directly from FORTRAN.

This package handles converting detector hit positions to and from 3d
vectors. Detector coordinates are specified by an x, y pair with x and y being
0 at the centre of the detector and having a range of -0.5 to 0.5.

Type:	     struct xy {
	         double x;
		 double y;
	     }; 
Description: A hit location on a detector.


Routine:     int coord_init(int n)
Description: Tell the package to reserve enough space to save the details
	     of n detectors. It returns 0 if all went well, 1 if it couldn't
	     get the memory.

Routine:     int coord_det(int n, FILE *fp)
Description: Read the coordinates of the corners of detector n from the file
	     specified by fp. The corners should be specified as four lines
	     each of the form:
	         x y z
	     Where x, y and z are relative to the origin of the coordinate
	     system, which should be the target for routines in the EV package
	     to work.

Routine:     int coord_andet(int i, FILE *fp)
Description: Read the position of detector n from the file specified by fp.
	     The detector position should be sepcified as:
	         thx thy w h r
	     Where thx and thy are the angle of the centre of the detector
	     specified as axial coordinates. w is the width of the detector,
	     h is its height and r is the distance from the origin of the
	     coordinate system (the target).

Routine:     int coord(int dt, struct xy *cp, struct vector *hp)
Description: Convert the detector hit position *cp on detector dt into a 3d
	     vector in hp.
To do:	     Decide if passing the hit location as a structure is overkill.

Routine:     int ndet_hit(int ndet, double th, double phi)
Description: Given a direction in spherical polar coordinates, calculate
	     which detector it hits from the detectors in the range 1..ndet.
	     The return value is the number of the detector that was hit.
To do:	     Provide some way of returning the position of the hit.

Routine:     int det_hit(int i, double th, double phi)
Description: Given a direction in spherical polar coordinates, calculate
	     if it hits detector i. Returns 1 for a hit, zero for a miss.
To do:	     Provide some way of returning the position of the hit.
	     Provide a similar routine that takes a normalised vector as
	     this would speed up ndet_hit().
	     Consider routines which get passed a vector structure.

Routine:     int inithitbins(double ts, double ps)
Description: Initisalise the hitbins array used by gethitbin. ts and ps
	     specify the number of bins per degree of theta and phi
	     respectively. If this funciton is called more than once it
	     automatically frees the memory for the old array and initialises
	     the new one to zero.

Routine:     void freehitbins(void)
Description: Frees the hitbin array to save memory.

Routine:     int *gethitbin(double theta, double phi)
Description: Convert floating point theta and phi into a pointer to a
	     bin. If inithitbins hasn't been called, then this routine
	     will automatically call it specifying 2 bins per degree.
To do:	     Decide if this routine should be part of the coord package.

Package: Reaction
-----------------

Relies on: nothing
C include file: evsubs.h
FORTRAN include file: evsubs.i

This package allows the user to manipulate the properties of the reaction
which is used by several other packages.

In C, the external variable
extern struct reac {
    double edisp;     /*energy dispersion*/
    double e1;        /*beam energy*/
    double p1;        /*beam momentum*/ 
    double mass[];    /*masses of the particles involved*/
    double q1;        /*reaction q value*/
    double vcm;       /*center of mass velocity*/
} reac;
holds the details of the reaction. At the moment it's free to be accessed
directly, but note that changing the values may confuse packages which rely
on them and so may give inconsistent results. It is recommended, therefore,
that even in C the user go through the reacs functions to set these values.
Using the reac_init call should also work fine.

Edisp holds the dispersion used to convert energy values in MeV into values
used by the programs. If, for example, you prefer all your energies to be
measured in keV, then set this to 1000.

E1 holds the beam energy. Divide by edisp to get MeV.

P1 holds the beam momentum. It is defined as sqrt(2*mass[1]*e1).

mass[1] is the mass of the projectile, mass[2] is the mass of the
target. mass[0] is used as a default mass of a detected particle by some other
packages.

q1 is not used at the moment.

vcm holds the centre of mass veolcity. It's defined as p1/(mass[1]+mass[2]).

At the time of writing, the reacs_* and reac_init functions do not guarantee
safety, so they should only be called before any routines in packages which
rely on this package.

Routine:     int reac_init(int type);
Description: Initialise the reaction package from the file
	     calib-inputs/reac.cal. This filenae is hardcoded. If you don't
	     wish to use this, then simply set all the members of the structure
	     listed above.
	     
	     The format of the file is:

	     beam_energy   dispersion
	     projectile_mass	target_mass
	     hitmass

	     Anything from a '*', '#' or '!' to the end of a line is ignored.

	     The beam_energy should be specified in MeV. It will be multiplied
	     by edisp before it's inserted into the reaction structure.

	     This function returns OK (in C) or SS_OK (in FORTRAN) if the file
	     loads OK, it returns ABORT (in C) or SS_ABORT (in FORTRAN) if
	     there's a problem.

Routine:     double reac_edisp(void)
	     double precision function read_edisp()
Description: Returns reac.edisp.

Routine:     void reacs_edisp(double value)
	     subroutine reac_edisp(double precision value)
Description: Sets reac.edisp.
	     
Routine:     double reac_e1(void)
	     double precision function read_e1()
Description: Returns reac.e1.

Routine:     void reacs_e1(double value)
	     subroutine reac_e1(double precision value)
Description: Sets reac.e1.
	     
Routine:     double reac_p1(void)
	     double precision function read_p1()
Description: Returns reac.p1.

Routine:     void reacs_p1(double value)
	     subroutine reac_p1(double precision value)
Description: Sets reac.p1.
	     
Routine:     double reac_mass(int i)
	     double precision function read_mass(integer i)
Description: Returns reac.mass[i].

Routine:     void reacs_mass(int i, double value)
	     subroutine reac_mass(integer i, double precision value)
Description: Sets reac.mass[i].
	     
Routine:     double reac_vcm(void)
	     double precision function read_vcm()
Description: Returns reac.vcm.

Routine:     void reacs_vcm(double value)
	     subroutine reac_vcm(double precision value)
Description: Sets reac.vcm.
	     
Package: Event-struct
---------------------

Relies on: Coord, Vector, Reaction
C include file: evsubs.h
FORTRAN include file: evsubs.i

This package allows the user to manipulate particle objects. The user can
set properties of a particle and read them back. 

Particle data is held in an opaque structure called ev_struct. Users should
not attempt to access the structure directly or make any assumptions about
its contents.

The following parameters are available for reading from a particle object:

v_x     X component of velocity
v_y	Y component of velocity
v_z	Z component of velocity
p	The momentum. This is actually handled by the vector package, so
	many properties of this can be requested.
e	Energy
etot	Running total of daughter energies
t	Time
pcm	The centre of mass momentum, handled by the vector package.
q	Excitation q
q2	Two body q-value
m	Mass
z	Charge
fold	Number of raw particles that have been added together to make this
	one.
hi	If fold>1 this is the identifier of the heavier daughter
li	If fold>1 this is the identifier of the lighter daughter
det	If fold=1 this is the detector number that the particle hit
seg	If fold=1 this is the segment within the detector that the particle
	hit.

v_x, v_y, v_z, e, etot, t, pcm, q, q2, m and z are double precision variables.
fold, hi, li, det and seg are integers.
p and pcm are vector structures.

Users should note that the particle velocity may be upgraded to use the
vector package.

There is one shared array of these particles which is available in both
FORTRAN and C. C users may also declare their own additional arrays of
these particles for private use. The scanga simulation package makes use of
this by using an array to simulate these particles leaving the shared array
free. C users can then, after reconstructing the particles into the shared
array, compare their results with the original particles in the separate,
private array.

As a consequence of this, most C routines in this package expect a pointer
to a particle structure so that the user may specify any particle anywhere
in memory. In contrast, the FORTRAN routines expect only an integer to give
the index of the particle into the shared array.

In C, the shared array can be accessed through the external pointer ev.

A second structure is defined to hold parameters relating to a whole group
of particles. This holds the following parameters:

int cmult[]   Channel multiplicities. cmult[n] holds the number of channels
	      that fired in detector n. cmult[0] holds the number of channels
	      that have fired in the whole system.
int pmult[]   Particle multiplicities. pmult[n] holds the number of particles
	      that hit detector n. pmult[0] holds the number of particles
	      that have hit the whole system.
int n[]	      Number of particles of each fold. n[1] holds the number of
	      singles particles, n[2] the number of particles constructed
	      out of 2 singles etc. n[0] holds the total number of particles
	      in the array.
int p[]	      Offset to the start of particles of fold n. p[1] is always
	      1 and in general p[n] is p[n-1]+n[n-1]
int type      The type of the event.
double etot   Etot for the reaction. This is usually the total of all the
	      singles particle energies.

cmult[] and pmult[] are advisory. The user may choose to keep them up to
date or not. No routines will break if they are not kept up to date
correctly.

n[] should always be kept up to date. Some routines will do this automatically.

p[] only need be kept up to date if the user wants to use it. No routine
    relies on the values in here, but some may update them.

type is purely advisory and for the users benefit. It is suggested that when
     the user identified the type of the event they place an identifying mark
     here for information.

etot should always be kept up to date. Some routines will do this
     automatically.

A variable of this structure is maintained for the shared array of particles
ev. In C this can be accessed through the external variable evhead.

Routine:     int ev_init(int n)
	     integer function ev_init(integer n)
Description: Sets the size of the shared particle array, that is the maximum
	     number of particles that can be stored there. Users should note
	     that element 0 of the array is unused, useful particles are
	     numbered 1..n inclusive.

	     Users would typically call this in their init subroutine in
	     Sunsort.

	     This function returns OK (in C) or SS_OK (in FORTRAN) if all
	     went well. It returns ABORT (in C) or SS_ABORT (in FORTRAN)
	     if the array couldn't be initialised.

	     Note that this function may be called more than once, but each
	     call initialises the array, so this call may not be used to
	     extend the array whilst preserving values.
To do:	     Why is element 0 unused ?
	     Is it safe to use particle 0 as scratch space ?

Routine:     void ev_zeroheader(void)
	     subroutine ev_zeroheader
Description: This function resets the event header to a safe state. Typically
	     this would be used at the start of sortin.



List of files
=============

File		Package		Provides
---------------	---------------	----------------------------------------------
./
detector.c	Structure	detector_init
		Markhits	detector_event
structure.c	Structure	loadexperiment
				setdetprocs
properties.c	Structure	initprops
				get/set...
fortprop.c	Structure	get/set...
loadadcs.c	ADCs		loadadcs
markhits.c	Markhits	initmarkhits
				markhits
				markhitslist
				loadgainoffset
				loadthresholds
rp.c		EVcalc		rp
nrp.c		EVcalc		nrp
				ncr
reac.c		EVcalc		reac_init
files.c		Internal	internal routines
crhit.c		EVcalc		rhit
				chit
				crhit
nrhit.c		EVcalc		nrhit
corr.c		EVcalc		corr
event_dump.c	Utility		chann_dump
		Structure	expt_dump
		Markhits	event_dump
		Utility		adclist_dump
		Utility		input_adcvals (broken)
coord.c		Coord		coord_init
				coord_det
				coord_andet
				coord
				ndet_hit
				det_hit
				gethitbin
missing_p.c	EVcalc		missing_p
plot_spec.c	Markhits	plot_chanspecs
		Utility		plot_hits
		EV		plot_cmult
		EV		plot_pmult
detprocs.c	-		Sample detector routines
nextgen.c	QuickStart	nextgen_init

event-struct/
ev.c		EV		ev_init
				ev_zeroheader
wrtev.c		EV		wrtev

simulations/
scanga.c	Scanga		not documented yet
scanga_inputs.c	Scanga		not documented yet
