\input cwebmac
% File:        sgfilter.w [CWEB source code]
% Residence:   http://jonsson.eu/programs/cweb/sgfilter/
% Created:     January 23, 2006 [v.1.0]
% Last change: December 4, 2011 [v.1.6]
% Author:      Fredrik Jonsson <http://jonsson.eu>
% Description: The CWEB source code for the SGFILTER stand-alone implementation
%              of the Savitzky-Golay smoothing filter. For information on the
%              CWEB programming language, see
%              http://www.literateprogramming.com.
% Compilation: Compile this program by using the enclosed Makefile, or use
%              the blocks of the Makefile as listed in the documentation
%              (file sgfilter.ps or sgfilter.pdf). The C source code (as
%              generated from this CWEB code) conforms to the ANSI standard
%              for the C programming language (which is equivalent to the
%              ISO C90 standard for C).
%
% Copyright (C) 2011, Fredrik Jonsson <http://jonsson.eu>
% Non-commercial copying welcome.
%
\input ext/epsf.tex   % For the inclusion of Encapsulated PostScript graphics
\input ext/eplain.tex % To access equation numbering and other
%cross-referencing
\def\version{1.6}
\def\lastrevdate{December 4, 2011}
\font\eightcmr=cmr8
\font\tensc=cmcsc10
\font\eightcmssq=cmssq8
\font\eightcmssqi=cmssqi8
\font\twentycmcsc=cmcsc10 at 20 truept
\def\sgfilter{{\eightcmr SGFILTER\spacefactor1000}}
\def\ANSI{{\eightcmr ANSI\spacefactor1000}} % The language standard we stick to
\def\GNU{{\eightcmr GNU\spacefactor1000}}       % GNU is Not Unix
\def\GCC{{\eightcmr GCC\spacefactor1000}}       % The GNU C-compiler
\def\CEE{{\eightcmr C\spacefactor1000}}         % The C programming language
\def\FORTRAN{{\eightcmr Fortran\spacefactor1000}} % The Fortran language
\def\CPP{\CEE{\tt++}}                           % The C++ programming language
\def\ANSICEE{{\eightcmr ANSI~C\spacefactor1000}}% The ANSI-C standard language
\def\CWEB{{\eightcmr CWEB\spacefactor1000}}     % The CWEB programming language
\def\UNIX{{\eightcmr UNIX\spacefactor1000}}
\def\CYGWIN{{\eightcmr CYGWIN\spacefactor1000}}
\def\GNUPLOT{{\eightcmr GNUPLOT\spacefactor1000}}
\def\CTANGLE{{\eightcmr CTANGLE\spacefactor1000}}
\def\CWEAVE{{\eightcmr CWEAVE\spacefactor1000}}
\def\mod{\mathop{\rm mod}\nolimits}  % The real part of a complex number
\def\re{\mathop{\rm Re}\nolimits}  % The real part of a complex number
\def\im{\mathop{\rm Im}\nolimits}  % The imaginary part of a complex number
\def\backslash{\char'134}          % The `\' character
\def\vertbar{\char'174}            % The `|' character
\def\dollar{\char'044}             % The `$' character
\def\tilde{\char'176}              % The `~' character
\def\tothepower{\char'136}         % The `^' character
\def\onehalf{{\textstyle{{1}\over{2}}}}
\def\threefourth{{\textstyle{{3}\over{4}}}}
\def\endalg{\vrule height 1.4ex width .6ex depth .4ex} % Rectangular bullet
\def\ie{i.\thinspace{e.}~\ignorespaces}
\def\eg{e.\thinspace{g.}~\ignorespaces}
\let\,\thinspace
%
% Define a handy macro for listing the steps of an algorithm.
%
\newdimen\aitemindent \aitemindent=26pt
\newdimen\aitemleftskip \aitemleftskip=36pt
\def\aitem[#1]{\smallbreak\noindent\hbox to 10pt{}%
  \hbox to\aitemindent{\bf #1\hfill}%
  \hangindent\aitemleftskip\ignorespaces}
%
% Define a handy macro for bibliographic references.
%
\newdimen\refitemindent \refitemindent=18pt
\def\refitem[#1]{\smallbreak\noindent%
  \hbox to\refitemindent{[#1]\hfill}%
  \hangindent\refitemindent\ignorespaces}
\def\references{\medskip\goodbreak\noindent{\bf References}\nobreak\smallskip}
%
% Define a handy macro for nicely typeset variable descriptions.
%
\newdimen\varitemindent \varitemindent=100pt
\def\varitem[#1]#2{\smallbreak\noindent\hbox to 20pt{}%
  \hbox to\varitemindent{#1\hfill}%
  \hangindent 120pt\ignorespaces#2\par}
%
% Define a handy macro for nicely typeset descriptions of command line options.
%
\newdimen\optitemindent \optitemindent=80pt
\def\optitem[#1]#2{\smallbreak\noindent\hbox to\hsize{\hskip40pt{#1}\hfill}
  \hangindent\optitemindent\ignorespaces{\hskip\optitemindent{#2}}\smallskip}
%
% Define a handy macro for the list of program revisions.
%
\newdimen\citemindent \citemindent=80pt
\newdimen\citemleftskip \citemleftskip=90pt
\def\citem[#1]{\smallbreak\noindent\hbox to 10pt{}%
  \hbox to\citemindent{\bf #1\hfill}%
  \hangindent\citemleftskip\ignorespaces}
\def\citindent{\smallbreak\noindent\hbox to 10pt{}%
  \hbox to\citemindent{\hfil}%
  \hangindent\citemleftskip\ignorespaces}
%
% Define a handy macro for the typesetting of quotes of text.
%
\newdimen\quoteindent \quoteindent=40pt
\def\quote#1{\par{\advance\leftskip by\quoteindent
  \advance\rightskip by\quoteindent
  \medskip\noindent{``#1''}\medskip}\par}
%
% Define a handy macro for the typesetting of figure captions. The double
% '{{' and '}}' are here in place to prevent the increased \leftskip and
% \rightskip to apply globally after the macro has been expanded.
%
\newdimen\figcapindent \figcapindent=\quoteindent
\def\figcaption[#1]#2{{\advance\leftskip by\figcapindent
  \advance\rightskip by\figcapindent
  \smallskip\noindent{\bf Figure #1.} {#2}\smallskip}}
%
% Define the \beginvrulealign and \endvrulealign macros as described in
% Donald Knuth's The TeXbook, Appendix D: Dirty Tricks. These macros are
% used in typesetting nicely looking tables.
%
\def\beginvrulealign{\setbox0=\vbox\bgroup}
\def\endvrulealign{\egroup % now \box0 holds the entire alignment
  \setbox0=\vbox{\setbox2=\hbox{\vrule height\ht0 depth\dp0 width0pt}
    \unvbox0 \setbox0=\lastbox % now \box0 is the bottom row
    \nointerlineskip \copy0 % put it back
    \global\setbox1=\hbox{} % initialize box that will contain rules
    \setbox4=\hbox{\unhbox0 % now open up the bottom row
      \loop \skip0=\lastskip \unskip % remove tabskip glue
      \advance\skip0 by-.4pt % rules are .4 pt wide
      \divide\skip0 by 2
      \global\setbox1=\hbox{\hskip\skip0\vrule\hskip\skip0
        \unhbox2\unhbox1}%
      \setbox2=\lastbox % remove alignment entry
      \ifhbox2 \setbox2=\hbox{\kern\wd2}\repeat}}%
  \hbox{\rlap{\box0}\box1}} % superimpose the alignment on the rules
%
% Make sure that the METAPOST logo can be loaded even in plain TeX.
%
\ifx\MP\undefined
    \ifx\manfnt\undefined
            \font\manfnt=logo10
    \fi
    \ifx\manfntsl\undefined
            \font\manfntsl=logosl10
    \fi
    \def\MP{{\ifdim\fontdimen1\font>0pt \let\manfnt = \manfntsl \fi
      {\manfnt META}\-{\manfnt POST}}\spacefactor1000 }%
\fi
\ifx\METAPOST\undefined \let\METAPOST=\MP \fi
\datethis


\N{1}{1}Introduction.
\vskip 120pt
\centerline{\twentycmcsc SGFilter}
\vskip 20pt
\centerline{A stand-alone implementation of the Savitzky--Golay smoothing
filter.}
\vskip 2pt
\centerline{(Version \version\ of \lastrevdate)}
\vskip 10pt
\centerline{Written by Fredrik Jonsson}
\vskip 10pt
\centerline{\epsfbox{fig0.1}}
\vfill\eject
\noindent
This document was automatically extracted from the \CWEB\ master source code
for the \sgfilter\ program and typeset in the Computer Modern typeface using
plain \TeX\ and \MP.
The source code and documentation of this
program is electronically available at
\.{http://jonsson.eu/programs/cweb/sgfilter/}.
\vfill
\line{Copyright \copyright\ Fredrik Jonsson \the\year\hfil}
\medskip
\noindent{All rights reserved. No part of this publication may be reproduced,
stored in a retrieval system, or transmitted, in any form, or by any means,
electronic, mechanical, photo-copying, recording, or otherwise, without the
prior consent of the author. Non-commercial copying welcome.\hfil}
\medskip
\line{Printed on \today, at \hours\hfil}
\medskip
\line{\TeX\ is a trademark of the American Mathematical Society\hfil}

\fi

\N{1}{2}The Savitzky--Golay smoothing filter.
The Savitzky--Golay smoothing filter was originally presented in 1964 by
Abraham Savitzky\footnote{$\dagger$}{Abraham Savitzky (1919--1999) was
an American analytical chemist. (Wikipedia)} and Marcel J.~E.
Golay\footnote{$\ddagger$}{Marcel J.~E.~Golay (1902--1989) was
a Swiss-born mathematician, physicist, and information theorist, who applied
mathematics to real-world military and industrial problems. (Wikipedia)}
in their paper ``Smoothing and Differentiation of Data by Simplified Least
Squares Procedures'', Anal.~Chem., {\bf 36}, 1627--1639 (1964).
% \.{http://dx.doi.org/10.1021/ac60214a047}
Being chemists and physicists, at the time of publishing associated with
the Perkin--Elmer Corporation (still today a reputable manufacturer of
equipment for spectroscopy), they found themselves often encountering noisy
spectra where simple noise-reduction techniques, such as running averages,
simply were not good enough for extracting well-determined characteristica
of spectral peaks.
In particular, any running averaging tend to flatten and widening peaks in
a spectrum, and as the peak width is an important parameter when determining
relaxation times in molecular systems, such noise-reduction techniques are
clearly non-desirable.

The main idea presented by Savitzky and Golay was a work-around avoiding the
problems encountered with running averages, while still maintaining the
smoothing of data and preserving features of the distribution such as relative
maxima, minima and width.
To quote the original paper on the target and purpose:
\quote{This paper is
concerned with computational methods for the removal of the random noise from
such information, and with the simple evaluation of the first few derivatives
of the information with respect to the graph abscissa.
[$\ldots$]
The objective here is to present specific methods for handling current
problems in the processing of such tables of analytical data. The methods
apply as well to the desk calculator, or to simple paper and pencil
operations for small amounts of data, as they do to the digital computer for
large amounts of data, since their major utility is to simplify and speed up
the processing of data.}

\fi

\M{3}The work-around presented by Savitzky and Golay for avoiding distortion of
peaks or features in their spectral data is essentially based on the
idea to perform a linear regression of some polynomial {\sl individually for
each sample}, followed by the {\sl evaluation of that polynomial exactly at the
very position of the sample}. While this may seem a plausible idea, the actual
task of performing a separate regression for each point easily becomes a very
time-consuming task unless we make a few observations about this problem.
However (and this is the key point in the method), for the regression of a
polynomial of a finite power, say of an order below 10, the coefficients
involved in the actual regression may be computed once and for all in an
early stage, followed by performing a {\sl convolution} of the discretely
sampled input data with the coefficient vector. As the coefficient vector
is significantly shorter than the data vector, this convolution is fast and
straightforward to implement.

The starting point in deriving the algorithm for the Savitzky--Golay smoothing
filter is to consider a smoothing method in which an equidistantly spaced
set of $M$ samples $f_n$, $n=1,\ldots,M$ are linearly combined to form a
filtered value $h_k$ according to\footnote{$\dagger$}{More generally,
Eq.~\eqref{eq:10} can be interpreted as a discretized version of the
convolution between a kernel $c(x)$ and a function $f(x)$,
$$
h(x)=\int^{\Delta_R}_{-\Delta_L}c(s) f(x+s)\,ds
\rightarrow\sum^{n_R}_{j=-n_L} c_j f_{k+j}.
$$
Notice, however, the different sign of $s$ as compared to the standard form
of the convolution integral in mathematics, where the argument of the
function usually yields ``$f(x-s)$''.}
$$
h_k=\sum^{n_R}_{j=-n_L} c_j f_{k+j},
\eqdef{eq:10}
$$
where $n_L$ is the number of samples ``to the left'' and $n_R$ the number of
samples ``to the right'' of the centre index $k$.
Notice that the running average smoothing corresponds to the case where
all coefficients $c_n$ are equal, with $c_n=1/(n_L+n_R+1)$.
The idea of the Savitzky--Golay filter is, however, to find the set of $c_n$
which better preserves the shape of features present in the sampled profile.
The approach is to make a linear regression of a polynomial to the $n_L+n_R+1$
samples in the window around sample $k$, and then evaluating this polynomial
at that very sample, for all $k$ from $1$ to $M$.

We consider the regression of an $m$:th degree polynomial
$$
p(x)=a_0+a_1(x-x_k)+a_2(x-x_k)^2+\ldots+a_m (x-x_k)^m
\eqdef{eq:20}
$$
to the set of $n_L$ samples to the left and $n_R$ to the right of sample $f_k$,
including the sample inbetween. Evaluating this polynomial at $x=x_k$ is
particularly easy, as we at that point simply have $p(x_k)=a_0$.
The linear regression of this polynomial to the samples $f_{k+j}$, with
$-n_L\le j\le n_R$, means that we look for the least-square approximated
solution to the linear system of $n_L+n_R+1$ equations
$$
\eqalign{
p(x_{k-n_L})&=a_0+a_1(x_{k-n_L}-x_k)+a_2(x_{k-n_L}-x_k)^2
+\ldots+a_m (x_{k-n_L}-x_k)^m\approx f_{k-n_L},\cr
&\hskip60pt\vdots\hskip100pt\vdots\cr
p(x_{k-1})&=a_0+a_1(x_{k-1}-x_k)+a_2(x_{k-1}-x_k)^2
+\ldots+a_m (x_{k-1}-x_k)^m\approx f_{k-1},\cr
p(x_{k})&=a_0\approx f_{k}\cr
p(x_{k+1})&=a_0+a_1(x_{k+1}-x_k)+a_2(x_{k+1}-x_k)^2
+\ldots+a_m (x_{k+1}-x_k)^m\approx f_{k+1},\cr
&\hskip60pt\vdots\hskip100pt\vdots\cr
p(x_{k+n_R})&=a_0+a_1(x_{k+n_R}-x_k)+a_2(x_{k+n_R}-x_k)^2
+\ldots+a_m (x_{k+n_R}-x_k)^m\approx f_{k+n_R},\cr
}
\eqdef{eq:30}
$$
which (under the assumption that $n_L+n_R+1>m+1$) provides an overdetermined
system for the $m+1$ coefficients $a_j$ which can be expressed in matrix
form as
$$
{\bf A}\cdot{\bf a}\equiv
\underbrace{
\pmatrix{
1&(x_{k-n_L}-x_k)&(x_{k-n_L}-x_k)^2&\cdots&(x_{k-n_L}-x_k)^m\cr
\vdots& &\vdots& &\vdots\cr
1&(x_{k-1}-x_k)&(x_{k-1}-x_k)^2&\cdots&(x_{k-1}-x_k)^m\cr
1&0&0&\cdots&0\cr
1&(x_{k+1}-x_k)&(x_{k+1}-x_k)^2&\cdots&(x_{k+1}-x_k)^m\cr
\vdots& &\vdots& &\vdots\cr
1&(x_{k+n_R}-x_k)&(x_{k+n_R}-x_k)^2&\cdots&(x_{k+n_R}-x_k)^m\cr
}
}_{[(n_L+n_R+1)\times(m+1)]}
\underbrace{
\pmatrix{
a_0\cr
a_1\cr
a_2\cr
\vdots\cr
a_m\cr
}
\vphantom{
\pmatrix{
()^m\cr
\vdots\cr
()^m\cr
1\cr
()^m\cr
\vdots\cr
()^m\cr
}
}
}_{[(m+1)\times1]}
=
\underbrace{
\pmatrix{
f_{k-n_L}\cr
\vdots\cr
f_{k-1}\cr
f_{k}\cr
f_{k+1}\cr
\vdots\cr
f_{k+n_R}\cr
}
\vphantom{
\pmatrix{
()^m\cr
\vdots\cr
()^m\cr
1\cr
()^m\cr
\vdots\cr
()^m\cr
}
}
}_{[(m+1)\times1]}
\equiv{\bf f}.
\eqdef{eq:40}
$$
The least squares solution to Eq.~\eqref{eq:40} is obtained by multiplying its
left- and right-hand sides by the transpose of the system matrix ${\bf A}$,
followed by solving the resulting $[(m+1)\times(m+1)]$-system of linear
equations for ${\bf a}$,
$$
{\bf A}^{\rm T}\cdot({\bf A}\cdot{\bf a})=
({\bf A}^{\rm T}\cdot{\bf A})\cdot{\bf a}=
{\bf A}^{\rm T}\cdot{\bf f}
\qquad\Leftrightarrow\qquad
{\bf a}=
({\bf A}^{\rm T}\cdot{\bf A})^{-1}\cdot
({\bf A}^{\rm T}\cdot{\bf f})
\eqdef{eq:50}
$$
Recapitulate that what we here target is the evaluation of $p(x_k)=a_0$, which
according to Eqs.~\eqref{eq:20} and~\eqref{eq:50} is equivalent to evaluating
the first (``zero:th'') row of the solution for ${\bf a}$, or
$$
p(x_k)=a_0=
\big[
\underbrace{
({\bf A}^{\rm T}\cdot{\bf A})^{-1}
}_{[(m+1)\times(m+1)]}
\cdot
\underbrace{
({\bf A}^{\rm T}\cdot{\bf f})
}_{[(m+1)\times1]}
\big]_{\{{\rm row\ }0\}}
\eqdef{eq:60}
$$
So, having arrived at this result for the regression, we clearly have a
solution for $a_0$ depending on the actual function values $f_{k+j}$ in the
vicinity of sample $f_k$. Doesn't this mean that we nevertheless need to
repeat the regression for every single sample to be included in the smoothing?
Moreover, how does the result presented in Eq.~\eqref{eq:60} relate to the
original mission, which we recapitulate was to find a general way of computing
the coefficients $c_j$ in the kernel of the convolution in Eq.~\eqref{eq:10}?

The answer to these questions lies in expanding Eq.~\eqref{eq:60} to yield the
expression for the first (``zero:th'') row as
$$
\eqalign{
p(x_k)=a_0
&=\big[
({\bf A}^{\rm T}\cdot{\bf A})^{-1}\cdot
({\bf A}^{\rm T}\cdot{\bf f})\big]_{\{{\rm row\ }0\}}\cr
&=\sum^{m+1}_{j=1}
\big[({\bf A}^{\rm T}\cdot{\bf A})^{-1}\big]_{0j}
\big[{\bf A}^{\rm T}\cdot{\bf f}\big]_{j}\cr
&=\sum^{m+1}_{j=1}
\big[({\bf A}^{\rm T}\cdot{\bf A})^{-1}\big]_{0j}
\sum^{m+1}_{k=1}\big[{\bf A}^{\rm T}\big]_{jk}\big[{\bf f}\big]_{k}\cr
}
\eqdef{eq:70}
$$
and observing that the $n$:th coefficient $c_n$ is obtained as equal to the
coefficient $a_0$ whenever ${\bf f}$ is replaced by the unit vector
${\bf e}_n$ (with all elements zero except for the unitary $n$:th element).
Hence
$$
\eqalign{
c_n&=\sum^{m+1}_{j=1}
\big[({\bf A}^{\rm T}\cdot{\bf A})^{-1}\big]_{0j}
\sum^{m+1}_{k=1}\big[{\bf A}^{\rm T}\big]_{jk}\big[{\bf e}_n\big]_{k}\cr
&=\sum^{m+1}_{j=1}
\big[({\bf A}^{\rm T}\cdot{\bf A})^{-1}\big]_{0j}
\sum^{m+1}_{k=1}\big[{\bf A}^{\rm T}\big]_{jk}\delta_{nk}\cr
&=\sum^{m+1}_{j=1}
\big[({\bf A}^{\rm T}\cdot{\bf A})^{-1}\big]_{0j}
\big[{\bf A}^{\rm T}\big]_{jn}\cr
&=\sum^{m+1}_{j=1}
\big[({\bf A}^{\rm T}\cdot{\bf A})^{-1}\big]_{0j}A_{nj}\cr
}
\eqdef{eq:80}
$$
This concludes the derivation of the coefficients in the Savitzky--Golay
filter, which may be computed once and for all in the beginning and afterwards
used as the (for any practical purposes short) kernel $c_j$ in the convolution
described by Eq.~\eqref{eq:10}.

\fi

\M{4}In 2000, editors James Riordon, Elizabeth Zubritsky, and Alan Newman of
{\sl Analytical Chemistry} made a review article of what they had identified
as the top-ten seminal papers in the history of the journal, based on the
number of citations.
Among the listed papers, of which some were written by Nobel-laureates-to-be,
the original paper by Savitzky and Golay makes a somewhat odd appearance, as
it not only concerns mainly numerical analysis, but also because it actually
includes \FORTRAN\ code for the implementation.
The review article\footnote{$\dagger$}{Available at
\.{http://pubs.acs.org/doi/pdf/10.1021/ac002801q}} concludes the discussion
of the Savitzky--Golay smoothing filter with a reminiscence by Abraham Savitzky
about the work:
\quote{In thinking about why the technique has been so widely used, I've come
to the following conclusions. First, it solves a common problem--the reduction
of random noise by the well-recognized least-squares technique. Second, the
method was spelled out in detail in the paper, including tables and a sample
computer subroutine. Third, the mathematical basis for the technique, although
explicitly and rigorously stated in the article, was separated from a
completely nonmathematical explanation and justification. Finally, the
technique itself is simple and easy to use, and it works.}

\fi

\M{5}As a final remark on the Savitzky--Golay filtering algorithm, a few points
on the actual implementation of the convolution need to be made.
While the \sgfilter\ program relies on the method for computation of the
Savitzky--Golay coefficients as presented in {\sl Numerical Recipes in C},
2nd Edn~(Cambridge University Press, New York, 1994), it must be emphasized
that the suggestion there presented for the convolution, which is to apply
the \PB{\\{convlv}} routine of {\sl Numerical Recipes in C}, is significantly
increasing the complexity and memory consumption in the filtering.
In particular, the \PB{\\{convlv}} routine in turn relies on consistent calls
to the
\PB{\\{twofft}} routine, which in order to deliver proper data needs to be
supplied
with a return vector of {\sl twice} the size of the input vector.
In addition, \PB{\\{convlv}} requires the size of the input vector to be of an
integer power of two (say, $M=1024$, $4096$, etc.), which may be acceptable
for one-off tests but is a rather inconvenient limitation for any more general
applications.

Whether the \sgfilter\ program should employ the convolution engine supplied by
the \PB{\\{convlv}} routine (recommended in {\sl Numerical Recipes in C}) or
the
direct convolution as implemented in the \PB{\\{sgfilter}} routine (recommended
by
me) is controlled by the \PB{\.{CONVOLVE\_WITH\_NR\_CONVLV}} definition in the
\.{sgfilter.h} header file. With reference to the above issues with \PB{%
\\{convlv}},
I strongly advise keeping the default (\.{0}) setting for
\PB{\.{CONVOLVE\_WITH\_NR\_CONVLV}}.

\fi

\N{1}{6}Revision history of the program.
\medskip
\citem[2006-01-18]{[v.1.0]} {\tt <fj@phys.soton.ac.uk>}\hfill\break
First properly working version of the \sgfilter\ program.

\citem[2006-01-20]{[v.1.1]} {\tt <fj@phys.soton.ac.uk>}\hfill\break
Added the test case for Savitzky--Golay filtering, modeling an underlying
function $g(x)$ with superimposed Gaussian noise as
$$
f(x)=\underbrace{
\cos(3x)\sin^2(x^3)+4\sum^4_{k=1}\exp(-(x-x_k)^2/w^2_k)
}_{g(x)} + \underbrace{Vu(x)\vphantom{\sum^4_{k=1}}}_{\rm noise}
$$
where $u(x)$ is a normally distributed stochastic variable of mean zero and
unit variance, $V$ is the local variance as specified arbitrarily, and the
remaining parameters $(x_k,w_k)$ are the positions and widths of four
Gaussian peaks superimposed onto the otherwise trigonometric expression
for the underlying function.

\citem[2006-01-21]{[v.1.2]} {\tt <fj@phys.soton.ac.uk>}\hfill\break
Changed the streaming of output (filtered) data so that the \PB{\\{stdout}}
stream
now is directed to file whenever \.{-o} or \.{\--outputfile} options are
present at the calling command line.

\citem[2006-05-06]{[v.1.3]} {\tt <fj@phys.soton.ac.uk>}\hfill\break
Added an introductory section documenting the derivation of the
Savitzky--Golay filter as such. Always nice to have at hand when it comes
to actually understanding why certain parameters in the filtering need to
be in certain ranges. Also added automatic support for extracting the number
of input samples automatically from the input file, hence making the \.{-M}
and \.{--num\_samples} option obsolete.

\citem[2006-05-06]{[v.1.4]} {\tt <fj@phys.soton.ac.uk>}\hfill\break
Replaced the convolution from the previously used \PB{\\{convlv}} routine to a
brute-force but more economical one, which now does not rely on the input
data being a set of $2^N$ samples for some $N$. However, I have chosen to
keep the old implementation, which can be re-applied simply by changing
the definition of \PB{\.{CONVOLVE\_WITH\_NR\_CONVLV}} to ``(\.{1}).''

\citem[2009-11-01]{[v.1.5]} {\tt <http://jonsson.eu>}\hfill\break
Included the \.{example.c} file in the \CWEB\ source of \sgfilter, for
automatically is generated from the master \CWEB\ source when passed through
\CTANGLE. A very nifty way indeed for keeping updated test cases.


\citem[2011-12-04]{[v.1.6]} {\tt <http://jonsson.eu>}\hfill\break
In the block concerned with the redirection of \PB{\\{stdout}} when delivering
filtered data, I found strange behaviour when executing \sgfilter\ under
Windows. What happens is that any redirection of \PB{\\{stdout}} back to
terminal
output in Windows naturally must be done in a different way than with the
\PB{$\\{freopen}(\.{"/dev/tty"},\.{"a"},\\{stdout})$} which is accepted by OS X
(Free BSD),
Linux, or any other \UNIX-like platforms. Hence, I simply added a (primitive)
check on the platform type in the header file.

\fi

\N{1}{7}Compiling the source code. The program is written in \CWEB, generating
\ANSICEE\ (ISO C99) conforming source code and documentation as plain
\TeX-source, and is to be compiled using the sequences as outlined in the
\.{Makefile} listed below.
For general information on literate programming, \CTANGLE, or \CWEAVE, see
\.{http://www.literateprogramming.com}.
\bigskip
{\obeylines\obeyspaces\tt
\#
\# Makefile designed for use with ctangle, cweave, gcc, and plain TeX.
\#
\# Copyright (C) 2002-2011, Fredrik Jonsson <http://jonsson.eu>
\#
\# The CTANGLE program converts a CWEB source document into a C program
\# which may be compiled in the usual way. The output file includes \#line
\# specifications so that debugging can be done in terms of the CWEB source
\# file.
\#
\# The CWEAVE program converts the same CWEB file into a TeX file that may
\# be formatted and printed in the usual way. It takes appropriate care of
\# typographic details like page layout and the use of indentation, italics,
\# boldface, etc., and it supplies extensive cross-index information that it
\# gathers automatically.
\#
\# CWEB allows you to prepare a single document containing all the informa-
\# tion that is needed both to produce a compilable C program and to produce
\# a well-formatted document describing the program in as much detail as the
\# writer may desire.  The user of CWEB ought to be familiar with TeX as well
\# as C.
\#
PROJECT  = sgfilter
CTANGLE  = ctangle
CWEAVE   = cweave
CC       = gcc
CCOPTS   = -O2 -Wall -ansi -std=iso9899:1999 -pedantic
LNOPTS   = -lm
TEX      = tex
DVIPS    = dvips
DVIPSOPT = -ta4 -D1200
PS2PDF   = ps2pdf
METAPOST = mpost
~   ~
all: \$(PROJECT) \$(PROJECT).pdf
~   ~
\$(PROJECT): \$(PROJECT).o
~        \$(CC) \$(CCOPTS) -o \$(PROJECT) \$(PROJECT).o \$(LNOPTS)
~   ~
\$(PROJECT).o: \$(PROJECT).c
~        \$(CC) \$(CCOPTS) -c \$(PROJECT).c
~   ~
\$(PROJECT).c: \$(PROJECT).w
~        \$(CTANGLE) \$(PROJECT) \$(PROJECT).c
~   ~
\$(PROJECT).pdf: \$(PROJECT).ps
~        \$(PS2PDF) \$(PROJECT).ps \$(PROJECT).pdf
~   ~
\$(PROJECT).ps: \$(PROJECT).dvi
~        \$(DVIPS) \$(DVIPSOPT) \$(PROJECT).dvi -o \$(PROJECT).ps
~   ~
\$(PROJECT).dvi: \$(PROJECT).tex
~        \$(TEX) \$(PROJECT).tex
~   ~
\$(PROJECT).tex: \$(PROJECT).w
~        \$(CWEAVE) \$(PROJECT)
~   ~
clean:
~        -rm -Rf \$(PROJECT) *~ *.c *.h *.o *.exe *.dat *.pdf *.mp *.trj *.mpx
~        -rm -Rf *.tex *.aux *.log *.toc *.idx *.scn *.dvi *.ps *.1 *.eps
~   ~
archive:
~        make -ik clean
~        tar --gzip --directory=../ -cf ../\$(PROJECT).tar.gz \$(PROJECT)
}
\bigskip
This \.{Makefile} essentially executes two major calls. First, the \CTANGLE\
program parses the \CWEB\ source file \.{sgfilter.w} to extract a \CEE\ source
file \.{sgfilter.c} which may be compiled into an executable program using any
\ANSICEE\ conformant compiler. The output source file \.{sgfilter.c} includes
\.{\#line} specifications so that any debugging conveniently can be done in
terms of line numbers in the original \CWEB\ source file \.{sgfilter.w}.
Second, the \CWEAVE\ program parses the same \CWEB\ source file \.{sgfilter.w}
to extract a plain \TeX\ file \.{sgfilter.tex} which may be compiled into a
PostScript or PDF document.
The document file \.{sgfilter.tex} takes appropriate care of typographic
details like page layout and text formatting, and supplies extensive
cross-indexing information which is gathered automatically.
In addition to extracting the documentary text, \CWEAVE\ also includes the
source code in cross-referenced blocks corresponding to the descriptors as
entered in the \CWEB\ source code.

Having executed \.{make} (or \.{gmake} for the \GNU\ enthusiast) in the same
directory where the files \.{sgfilter.w} and \.{Makefile} are located, one is
left with the executable file \.{sgfilter}, being the ready-to-use compiled
program, and the PostScript file \.{sgfilter.ps} (or PDF file \.{sgfilter.pdf})
which contains the full documentation of the program, that is to say the
document you currently are reading.
Notice that on platforms running any operating system by Microsoft, the
executable file will instead automatically be named \.{sgfilter.exe}.
This convention also applies to programs compiled under the \UNIX-like
environment \CYGWIN.

\fi

\N{1}{8}Running the program. The program is entirely controlled by the command
line options supplied when invoking the program. The syntax for executing the
program is\par
\medskip
\line{\hskip 40pt\.{sgfilter [options]}\hfill}\par
\medskip
\noindent
where \.{options} include the following, given in their long as well as
their short forms (with prefixes `\.{--}' and `\.{-}', respectively):
\medskip
\optitem[\.{--inputfile}, \.{-i} $\langle${\it input filename}$\rangle$]%
{Specifies the raw, unfiltered input data to be crunched. The input file
should describe the input as two columns containing $x$- and $y$-coordinates
of the samples.}
\optitem[\.{--outputfile}, \.{-o} $\langle${\it output filename}$\rangle$]%
{Specifies the output file to which the program should write the filtered
profile, again in a two-column format containing $x$- and $y$-coordinates
of the filtered samples. If this option is omitted, the generated
filtered data will instead be written to the console (terminal).}
\optitem[\.{-nl} $\langle n_L\rangle$]%
{Specifies the number of samples $n_L$ to use to the ``left'' of the basis
sample in the regression window (kernel). The total number of samples in
the window will be $nL+nR+1$.}
\optitem[\.{-nr} $\langle n_R\rangle$]%
{Specifies the number of samples $n_R$ to use to the ``right'' of the basis
sample in the regression window (kernel). The total number of samples in
the window will be $nL+nR+1$.}
\optitem[\.{-m} $\langle m\rangle$]%
{Specifies the order $m$ of the polynomial
$p(x)=a_0+a_1(x-x_k)+a_2(x-x_k)^2+\ldots+a_m (x-x_k)^m$ to use in the
regression analysis leading to the Savitzky--Golay coefficients.
Typical values are between $m=2$ and $m=6$. Beware of too high values,
which easily makes the regression too sensitive, with an oscillatory
result.}
\optitem[\.{-ld} $\langle l_D\rangle$]%
{Specifies the order of the derivative to extract from the Savitzky--Golay
smoothing algorithm. For regular Savitzky--Golay smoothing of the input
data as such, use $l_D=0$. For the Savitzky--Golay smoothing and extraction
of derivatives, set $l_D$ to the order of the desired derivative and make
sure that you correctly interpret the scaling parameters as described in
{\sl Numerical Recipes in C}, 2nd Edn~(Cambridge University Press, New
York, 1994).}
\optitem[\.{--help}, \.{-h}]%
{Displays a brief help message and terminates the \sgfilter\ program clean
from any error codes.}
\optitem[\.{--verbose}, \.{-v}]%
{Toggle verbose mode. (Default: Off.) This option should always be omitted
whenever no output file has been specified (that is to say, omit any
\.{--verbose} or \.{-v} option whenever \.{--outputfile} or \.{-o} has
been omitted), as the verbose logging otherwise will contaminate the
filtered data stream written to the console (terminal).}

\fi

\N{1}{9}Example of Savitzky--Golay filtering with the \sgfilter\ program.
It is always a good idea to create a rather ``nasty'' test case for an
algorithm, and in this case it also provides the reader of this code with
a (hopefully) clear example of usage of the \sgfilter\ program.

We start off with generating a test suite of noisy data, in this case
modeling an underlying function $g(x)$ with superimposed Gaussian noise as
$$
f(x)=\underbrace{
\cos(3x)\sin^2(x^3)+4\sum^4_{k=1}\exp(-(x-x_k)^2/w^2_k)
}_{g(x)} + \underbrace{Vu(x)\vphantom{\sum^4_{k=1}}}_{\rm noise}
$$
where $u(x)$ is a normally distributed stochastic variable of mean zero and
unit variance, $V$ is the local variance as specified arbitrarily, and the
remaining parameters $(x_k,w_k)$ are the positions and widths of four
Gaussian peaks superimposed onto the otherwise trigonometric expression
for the underlying function. For the current test suite we use
$(x_1,w_1)=(0.2,0.007)$, $(x_2,w_2)=(0.4,0.01)$, $(x_3,w_3)=(0.6,0.02)$,
and $(x_4,w_4)=(0.8,0.04)$. These Gaussian peaks serve as to provide various
degrees of rapidly varying data, to check the performance in finding maxima.
Meanwhile, the less rapidly varying domains which are dominated by the
trigonometric expression serves as a test for the capability of the filter
to handle rather moderate variations of low amplitude.

The underlying test function $g(x)$ is shown\footnote{$\dagger$}{See the
\.{*.eps} blocks in the enclosed \.{Makefile} for details on how \METAPOST
was used in the generation of the encapsulated PostScript images shown in
Figs.~1--6.} in Fig.~1.
\medskip
\centerline{\epsfbox{fig1.1}}
\figcaption[1]{The underlying test function $g(x)=\cos(3x)\sin^2(x^3)%
+4\sum^4_{k=1}\exp(-(x-x_k)^2/w^2_k)$ without any added noise.
Here the positions and widths of the Gaussian peaks are
$(x_1,w_1)=(0.2,0.007)$,
$(x_2,w_2)=(0.4,0.01)$, $(x_3,w_3)=(0.6,0.02)$, and $(x_4,w_4)=(0.8,0.04)$.}
\medskip
\noindent
The generator of artificial test data to be tested by the Savitsky--Golay
filtering algorithm is here included as a simple \CEE\ program, which
automatically is generated from the master \CWEB\ source when passed through
\CTANGLE.

\Y\B\4\X9:\.{example.c }\X${}\E{}$\6
\8\#\&{include} \.{<stdio.h>}\6
\8\#\&{include} \.{<stdlib.h>}\6
\8\#\&{include} \.{<time.h>}\6
\8\#\&{include} \.{<math.h>}\6
\8\#\&{define} \.{TWOPI} \5${}(\T{2.0}*\T{3.141592653589793}){}$\6
\&{float} \\{gauss}(\&{float} \|x${},\39{}$\&{float} \|w${},\39{}$\&{float} %
\\{xa})\1\1\2\2\6
${}\{{}$\1\6
\&{return} ${}(\\{exp}({-}\\{pow}(((\|x-\\{xa})/\|w),\39\T{2})));{}$\6
\4${}\}\3{-1}{}$\2\7
\&{float} \\{func}(\&{float} \|x)\1\1\2\2\6
${}\{{}$\1\6
\&{float} \\{retval}${}\K\\{gauss}(\|x,\39\T{0.007},\39\T{0.2}){}$;\C{
$x_1=0.2$, $w_1=0.007$ }\7
${}\\{retval}\MRL{+{\K}}\\{gauss}(\|x,\39\T{0.01},\39\T{0.4}){}$;\C{ $x_2=0.4$,
$w_2=0.01$ }\6
${}\\{retval}\MRL{+{\K}}\\{gauss}(\|x,\39\T{0.02},\39\T{0.6}){}$;\C{ $x_3=0.6$,
$w_3=0.02$ }\6
${}\\{retval}\MRL{+{\K}}\\{gauss}(\|x,\39\T{0.04},\39\T{0.8}){}$;\C{ $x_4=0.8$,
$w_4=0.04$ }\6
${}\\{retval}\MRL{*{\K}}\T{4.0};{}$\6
${}\\{retval}\MRL{+{\K}}\\{cos}(\T{3.0}*\|x)*\\{pow}(\\{sin}(\\{pow}(\|x,\39%
\T{3})),\39\T{2});{}$\6
\&{return} (\\{retval});\6
\4${}\}\3{-1}{}$\2\7
\&{int} \\{main}(\&{int} \\{argc}${},\39{}$\&{char} ${}{*}\\{argv}[\,]){}$\1\1%
\2\2\6
${}\{{}$\1\6
\&{int} \|k${},{}$ \\{mm}${}\K\T{1024};{}$\6
\&{float} \\{var}${}\K\T{1.0},{}$ \\{xmax}${}\K\T{2.5},{}$ \\{x1}${},{}$ %
\\{x2}${},{}$ \|u${},{}$ \|v${},{}$ \|f${},{}$ \|z;\7
\&{if} ${}(\\{argc}>\T{1}){}$\1\5
${}\\{sscanf}(\\{argv}[\T{1}],\39\.{"\%f"},\39{\AND}\\{var}){}$;\C{ Read first
argument as variance }\2\6
\\{srand}((\&{unsigned}) \\{time}${}(\NULL)){}$;\C{ Initialize random number
generator }\6
\&{for} ${}(\|k\K\T{0};{}$ ${}\|k<\\{mm}-\T{1};{}$ ${}\|k\MRL{+{\K}}\T{2}){}$\5
${}\{{}$\1\6
${}\\{x1}\K\\{xmax}*\|k/{}$((\&{double}) \\{mm}${}-\T{1});{}$\6
${}\\{x2}\K\\{xmax}*(\|k+\T{1})/{}$((\&{double}) \\{mm}${}-\T{1});{}$\6
${}\|u\K{}$((\&{float}) \\{rand}(\,))${}/\.{RAND\_MAX}{}$;\C{ Uniformly
distributed over $[0,1]$ }\6
${}\|v\K{}$((\&{float}) \\{rand}(\,))${}/\.{RAND\_MAX}{}$;\C{ Uniformly
distributed over $[0,1]$ }\6
\&{if} ${}(\|u>\T{0.0}){}$\5
${}\{{}$\C{ Apply the Box--Muller algorithm on \PB{\|u} and \PB{\|v} }\1\6
${}\|f\K\\{sqrt}({-}\T{2}*\\{log}(\|u));{}$\6
${}\|z\K\.{TWOPI}*\|v;{}$\6
${}\|u\K\|f*\\{cos}(\|z){}$;\C{ Normally distributed with E(\PB{\|u})=0 and
Var(\PB{\|u})=1 }\6
${}\|v\K\|f*\\{sin}(\|z){}$;\C{ Normally distributed with E(\PB{\|u})=0 and
Var(\PB{\|u})=1 }\6
${}\\{fprintf}(\\{stdout},\39\.{"\%1.8f\ \%1.8f\\n"},\39\\{x1},\39\\{func}(%
\\{x1})+\\{var}*\|u){}$;\C{ $f(x_1)$ }\6
${}\\{fprintf}(\\{stdout},\39\.{"\%1.8f\ \%1.8f\\n"},\39\\{x2},\39\\{func}(%
\\{x2})+\\{var}*\|v){}$;\C{ $f(x_2)$ }\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\&{return} (\T{0});\6
\4${}\}{}$\2\par
\fi

\M{10}After having compiled the above code \.{example.c}, simply run
\.{./example }$\langle${\it noise variance}$\rangle$\.{ > }$\langle$%
{\it file name}$\rangle$ in order to generate the test function with a
superimposed normally distributed (gaussian) noise of desired variance.
In particular, we will in this test suite consider variances of 0 (that is to
say, the underlying function without any noise), 0.5, 1.0, and 2.0.
Such data files are simply generated by executing\footnote{$\dagger$}{The
resulting test data, which so far has not been subject to any filtering,
may easily be viewed by running the following script in Octave/Matlab:
\medskip
{\obeylines\obeyspaces\tt
clear all; close all;
hold on;
u=load('example-2.0.dat'); plot(u(:,1),u(:,2),'-b');
u=load('example-1.0.dat'); plot(u(:,1),u(:,2),'-c');
u=load('example-0.5.dat'); plot(u(:,1),u(:,2),'-r');
u=load('example-0.0.dat'); plot(u(:,1),u(:,2),'-k');
legend('var(f(x))=2.0','var(f(x))=1.0','var(f(x))=0.5','var(f(x))=0.0');
hold off;
title('Artificial data generated for tests of Savitzky-Golay filtering');
xlabel('x');
ylabel('f(x)');
}
}
\bigskip
{\obeylines\obeyspaces\tt
./example 0.0 > example-0.0.dat
./example 0.5 > example-0.5.dat
./example 1.0 > example-1.0.dat
./example 2.0 > example-2.0.dat
}
\bigskip
\noindent
The resulting ``noisified'' suite of test data are in Figs.~2--4 shown for the
respective noise variances of $V=0.5$, $V=1.0$, and $V=2.0$, respectively.
\medskip
\centerline{\epsfbox{fig2.1}}
\figcaption[2]{The test function $g(x)$ with added Gaussian noise of variance
$V=2.0$, as stored in file \.{example-2.0.dat} in the test suite.}

\fi

\M{11}Applying the Savitzky--Golay filter to the test data is now a
straightforward
task.
Say that we wish to test filtering with polynomial degree $\PB{\|m}=4$ and $%
\PB{\\{ld}}=0$
(which is the default value of \PB{\\{ld}}, for regular smoothing with a
delivered
``zero:th order derivative'', that is to say the smoothed non-differentiated
function), for the two cases
$\PB{\\{nl}}=\PB{\\{nr}}=10$ (in total 21 points in the regression kernel) and
$\PB{\\{nl}}=\PB{\\{nr}}=60$ (in total 121 points in the regression kernel).
Using the previously generated test suite of noisy data, the filtering is then
easily accomplished by executing:
\bigskip
{\obeylines\obeyspaces\tt
./sgfilter -m 4 -nl 60 -nr 60 -i example-0.0.dat -o example-0.0-f-60.dat
./sgfilter -m 4 -nl 10 -nr 10 -i example-0.0.dat -o example-0.0-f-10.dat
./sgfilter -m 4 -nl 60 -nr 60 -i example-0.5.dat -o example-0.5-f-60.dat
./sgfilter -m 4 -nl 10 -nr 10 -i example-0.5.dat -o example-0.5-f-10.dat
./sgfilter -m 4 -nl 60 -nr 60 -i example-1.0.dat -o example-1.0-f-60.dat
./sgfilter -m 4 -nl 10 -nr 10 -i example-1.0.dat -o example-1.0-f-10.dat
./sgfilter -m 4 -nl 60 -nr 60 -i example-2.0.dat -o example-2.0-f-60.dat
./sgfilter -m 4 -nl 10 -nr 10 -i example-2.0.dat -o example-2.0-f-10.dat
}
\bigskip
\noindent
The resulting filtered data sets are shown in Figs.~3--6 for noise variances
of $V=2.0$, $V=1.0$, $V=0.5$, and $V=0$, respectively. The final case
corresponds to the interesting case of filtering the underlying function
$g(x)$ without any added noise whatsoever, which corresponds to performing
a local regression of the regression polynomial to the analytical trigonometric
and exponential functions being terms of $g(x)$, a regression where we by no
means should expect a perfect match.
\medskip
\centerline{\epsfbox{fig3.1}}
\figcaption[3]{The profiles resulting from Savitzky--Golay-filtering of the
test function $g(x)$ with added Gaussian noise of variance
$V=2.0$.}
\medskip
As can be seen in Fig.~3, the results from filtering the ``worst-case'' set
(with noise variance $V=2.0$) with $\PB{\\{nl}}=\PB{\\{nr}}=10$ ($\PB{\\{nl}}+%
\PB{\\{nr}}+1=21$ samples
in the regression kernel) and $\PB{\|m}=4$ (curve in blue) yield a rather good
tracking of the narrow Gaussian peaks, meanwhile performing rather poor in
the low-amplitude and rather slowly varying trigonometric hills in the
right-hand side of the graph.
As a reference, the underlying function $g(x)$ is mapped in dashed black.
On the other hand, with $\PB{\\{nl}}=\PB{\\{nr}}=60$ ($\PB{\\{nl}}+\PB{%
\\{nr}}+1=121$ samples in the
regression kernel) and keeping the same degree of the
regression polynomial (curve in red), the narrow peaks are barely followed,
meanwhile having a rather poor performance in the slowly varying hills as
well (albeit of a very poor signal-to-noise ratio).
\vfill\eject

However, with a lower variance of the superimposed noise, we at $V=1$ have a
nice tracking of the slowly varying hills by the 121-sample regression kernel,
as shown in Fig.~4, meanwhile having a good tracking of the narrow Gaussian
peaks by the 21-sample regression kernel.
That the $\PB{\\{nl}}+\PB{}=21$-sample window is noisier than the 121-sample
one should
not really be surprising, as the higher number of samples in the regression
window tend to smoothen out the regression even further.

\centerline{\epsfbox{fig4.1}}
\figcaption[4]{The profiles resulting from Savitzky--Golay-filtering of the
test function $g(x)$ with added Gaussian noise of variance
$V=1.0$.}
\medskip
\centerline{\epsfbox{fig5.1}}
\figcaption[5]{The profiles resulting from Savitzky--Golay-filtering of the
test function $g(x)$ with added Gaussian noise of variance
$V=0.5$.}
\vfill\eject

\centerline{\epsfbox{fig6.1}}
\figcaption[6]{The profiles resulting from Savitzky--Golay-filtering of the
test function $g(x)$ with added Gaussian noise of variance
$V=0$, that is to say a direct regression against the underlying function
$g(x)$. This figure illustrates the limitations of the attempts of
linear regression of a polynomial to an underlying function which
clearly cannot be approximated by a simple polynomial expressin in
certain domains. One should always keep this limitation in mind before
accepting (or discarding) data filtered by the Savitzky--Golay algorithm,
despite the many cases in which it performs exceptionally well.}
\vfill\eject

\fi

\N{1}{12}Header files. We put the interface part of our routines in the header
file
\.{sgfilter.h}, and we restrict ourselves to a lowercase file name to
maintain portability among operating systems with case-insensitive file names.
There are just a few global definitions present in the \sgfilter\ program:\par
\varitem[\PB{\.{VERSION}}]{The current program revision number.}
\varitem[\PB{\.{COPYRIGHT}}]{The copyright banner.}
\varitem[\PB{\.{DEFAULT\_NL}}]{The default value to use for the \PB{\\{nl}}
variable unless
stated otherwise at the command line during startup of the program.
This parameter specifies the number of samples $n_L$ to use to the ``left''
of the basis sample in the regression window (kernel). The total number of
samples in the window will be $nL+nR+1$.}
\varitem[\PB{\.{DEFAULT\_NR}}]{The default value to use for the \PB{\\{nr}}
variable unless
stated otherwise at the command line during startup of the program.
This parameter specifies the number of samples $n_R$ to use to the ``right''
of the basis sample in the regression window (kernel). The total number of
samples in the window will be $nL+nR+1$.}
\varitem[\PB{\.{DEFAULT\_M}}]{The default value to use for the \PB{\|m}
variable unless
stated otherwise at the command line during startup of the program.
This parameter specifies the order $m$ of the polynomial
$p(x)=a_0+a_1(x-x_k)+a_2(x-x_k)^2+\ldots+a_m (x-x_k)^m$ to use in the
regression analysis leading to the Savitzky--Golay coefficients.
Typical values are between $m=2$ and $m=6$. Beware of too high values,
which easily makes the regression too sensitive, with an oscillatory
result.}
\varitem[\PB{\.{DEFAULT\_LD}}]{The default value to use for the \PB{\\{ld}}
variable unless
stated otherwise at the command line during startup of the program.
This parameter specifies the order of the derivative to extract from the
Savitzky--Golay smoothing algorithm.
For regular Savitzky--Golay smoothing of the input
data as such, use $l_D=0$. For the Savitzky--Golay smoothing and extraction
of derivatives, set $l_D$ to the order of the desired derivative and make
sure that you correctly interpret the scaling parameters as described in
{\sl Numerical Recipes in C}, 2nd Edn~(Cambridge University Press, New
York, 1994).}
\varitem[\PB{\.{NCHMAX}}]{The maximum number of characters allowed in strings
for
storing file names, including path.}
\varitem[\PB{$\\{log}(\,\ldots\,)$}]{The \PB{\\{log}(\,)} macro forms the user
interface to run-time
error messaging and console logging activities, by invoking the
\PB{\\{log\_printf}(\,)} routine. The \PB{\\{log}(\,)} macro is preferrably
used rather than
direct calls to \PB{\\{log\_printf}(\,)}, as it automatizes the extraction of
the
calling routine, via the \PB{\\{\_\_func\_\_}} macro. Notice that the clean
construction
of the macro using variable-length arguments (via \PB{\.{\_\_VA\_ARGS\_\_}}) {%
\sl only} is
supported at ISO 9899:1999 (ISO C99) standard level or above (see, for
example, \.{http://en.wikipedia.org/wiki/C99}), which is the default
compliance level used in the enclosed \.{Makefile}. (In fact, this is here
{\sl the} very reason for using ISO 9899:1999 rather than ISO 9899:1990).}

\Y\B\4\X12:\.{sgfilter.h }\X${}\E{}$\6
\8\#\&{define} \.{VERSION} \5\.{"1.6"}\6
\8\#\&{define} \.{COPYRIGHT} \5\.{"Copyright\ (C)\ 2006-}\)\.{2011,\ Fredrik\
Jonsso}\)\.{n"}\6
\8\#\&{define} \.{DEFAULT\_NL} \5(\T{15})\6
\8\#\&{define} \.{DEFAULT\_NR} \5(\T{15})\6
\8\#\&{define} \.{DEFAULT\_M} \5(\T{4})\6
\8\#\&{define} \.{DEFAULT\_LD} \5(\T{0})\6
\8\#\&{define} \.{EPSILON} \5((\&{double})(\T{1.0\_-20}))\6
\8\#\&{define} \.{NCHMAX} \5(\T{256})\6
\8\#\&{define} \.{CONVOLVE\_WITH\_NR\_CONVLV} \5(\T{0})\6
\8\#\&{define} ${}\\{log}(\,\ldots\,)\\{log\_printf} \5(\\{\_\_func\_\_},\39\.{%
\_\_VA\_ARGS\_\_}){}$\6
\8\#\&{if} \&{defined} (\.{\_CYGWIN\_SIGNAL\_H})${}\V{}$\&{defined} (\.{\_%
\_APPLE\_\_})${}\V{}$\&{defined} (\\{\_\_unix\_\_})${}\V{}$\&{defined} (\\{\_%
\_linux})\6
\8\#\&{define} \.{UNIX\_LIKE\_OS} \5(\T{1})\6
\8\#\&{endif}\6
\&{void} \\{log\_printf}(\&{const} \&{char} ${}{*}\\{function\_name},\39{}$%
\&{const} \&{char} ${}{*}\\{format},\39\,\ldots\,);{}$\6
\&{int} ${}{*}{}$\\{ivector}(\&{long} \\{nl}${},\39{}$\&{long} \\{nh});\6
\&{double} ${}{*}{}$\\{dvector}(\&{long} \\{nl}${},\39{}$\&{long} \\{nh});\6
\&{double} ${}{*}{*}{}$\\{dmatrix}(\&{long} \\{nrl}${},\39{}$\&{long} %
\\{nrh}${},\39{}$\&{long} \\{ncl}${},\39{}$\&{long} \\{nch});\6
\&{void} \\{free\_ivector}(\&{int} ${}{*}\|v,\39{}$\&{long} \\{nl}${},\39{}$%
\&{long} \\{nh});\6
\&{void} \\{free\_dvector}(\&{double} ${}{*}\|v,\39{}$\&{long} \\{nl}${},\39{}$%
\&{long} \\{nh});\6
\&{void} \\{free\_dmatrix}(\&{double} ${}{*}{*}\|m,\39{}$\&{long} \\{nrl}${},%
\39{}$\&{long} \\{nrh}${},\39{}$\&{long} \\{ncl}${},\39{}$\&{long} \\{nch});\6
\&{void} \\{lubksb}(\&{double} ${}{*}{*}\|a,\39{}$\&{int} \|n${},\39{}$\&{int}
${}{*}\\{indx},\39{}$\&{double} \|b[\,]);\6
\&{void} \\{ludcmp}(\&{double} ${}{*}{*}\|a,\39{}$\&{int} \|n${},\39{}$\&{int}
${}{*}\\{indx},\39{}$\&{double} ${}{*}\|d);{}$\6
\&{void} \\{four1}(\&{double} \\{data}[\,]${},\39{}$\&{unsigned} \&{long} %
\\{nn}${},\39{}$\&{int} \\{isign});\6
\&{void} \\{twofft}(\&{double} \\{data1}[\,]${},\39{}$\&{double} \\{data2}[%
\,]${},\39{}$\&{double} \\{fft1}[\,]${},\39{}$\&{double} \\{fft2}[\,]${},\39{}$%
\&{unsigned} \&{long} \|n);\6
\&{void} \\{realft}(\&{double} \\{data}[\,]${},\39{}$\&{unsigned} \&{long} %
\|n${},\39{}$\&{int} \\{isign});\6
\&{char} \\{convlv}(\&{double} \\{data}[\,]${},\39{}$\&{unsigned} \&{long} %
\|n${},\39{}$\&{double} \\{respns}[\,]${},\39{}$\&{unsigned} \&{long} \|m${},%
\39{}$\&{int} \\{isign}${},\39{}$\&{double} \\{ans}[\,]);\6
\&{char} \\{sgcoeff}(\&{double} \|c[\,]${},\39{}$\&{int} \\{np}${},\39{}$%
\&{int} \\{nl}${},\39{}$\&{int} \\{nr}${},\39{}$\&{int} \\{ld}${},\39{}$\&{int}
\|m);\6
\&{char} \\{sgfilter}(\&{double} \\{yr}[\,]${},\39{}$\&{double} \\{yf}[\,]${},%
\39{}$\&{int} \\{mm}${},\39{}$\&{int} \\{nl}${},\39{}$\&{int} \\{nr}${},\39{}$%
\&{int} \\{ld}${},\39{}$\&{int} \|m);\6
\&{char} ${}{*}{}$\\{strip\_away\_path}(\&{char} \\{filename}[\,]);\6
\&{long} \&{int} \\{num\_coordinate\_pairs}(\&{FILE} ${}{*}\\{file}){}$;\par
\fi

\N{1}{13}The main program. Here follows the general outline of the \PB{%
\\{main}} routine of
the \sgfilter\ program. This is where it all starts.

\Y\B\X14:Library inclusions\X\6
\X15:Global variables\X\6
\X22:Definitions of routines\X\7
\&{int} \\{main}(\&{int} \\{argc}${},\39{}$\&{char} ${}{*}\\{argv}[\,]){}$\1\1%
\2\2\6
${}\{{}$\1\6
\X16:Definition of variables\X\6
\X17:Parse command line for options and parameters\X\6
\X18:Allocate memory and read \PB{\|M} samples of unfiltered data from file\X\6
\X19:Filter raw data through the Savitzky--Golay smoothing filter\X\6
\X20:Write filtered data to file or terminal output\X\6
\X21:Deallocate memory\X\6
\&{return} (\.{EXIT\_SUCCESS});\6
\4${}\}{}$\2\par
\fi

\M{14}Library dependencies.
The standard \ANSICEE\ libraries included in this program are:\par
\varitem[\.{math.h}]{For access to common mathematical functions.}
\varitem[\.{stdio.h}]{For file access and any block involving \PB{%
\\{fprintf}}.}
\varitem[\.{stdlib.h}]{For access to the \PB{\\{exit}} function.}
\varitem[\.{stdarg.h}]{For access to \PB{\\{vsprintf}}, \PB{\\{vfprintf}} etc.}
\varitem[\.{string.h}]{For string manipulation, \PB{\\{strcpy}}, \PB{%
\\{strcmp}} etc.}
\varitem[\.{ctype.h}]{For access to the \PB{\\{isalnum}} function.}
\varitem[\.{time.h}]{For access to \PB{\\{ctime}}, \PB{\\{clock}} and time
stamps.}
\varitem[\.{sys/time.h}]{For access to millisecond-resolved timer.}

\Y\B\4\X14:Library inclusions\X${}\E{}$\6
\8\#\&{include} \.{<math.h>}\6
\8\#\&{include} \.{<stdlib.h>}\6
\8\#\&{include} \.{<stdarg.h>}\6
\8\#\&{include} \.{<stdio.h>}\6
\8\#\&{include} \.{<string.h>}\6
\8\#\&{include} \.{<ctype.h>}\6
\8\#\&{include} \.{<time.h>}\6
\8\#\&{include} \.{<sys/time.h>}\6
\8\#\&{include} \.{"sgfilter.h"}\par
\U13.\fi

\M{15}Declaration of global variables. The only global variables allowed in
my programs are \PB{\\{optarg}}, which is a pointer to the the string of
characters
that specified the call from the command line, and \PB{\\{progname}}, which
simply
is a pointer to the string containing the name of the program, as it was
invoked from the command line.
Typically, the \PB{\\{progname}} string is the result remaining after having
passed
\PB{\\{argv}[\T{0}]} through the \PB{\\{strip\_away\_path}} routine, just
before parsing the
command line for parameters.

\Y\B\4\X15:Global variables\X${}\E{}$\6
\&{extern} \&{char} ${}{*}\\{optarg};{}$\6
\&{char} ${}{*}\\{progname}{}$;\par
\U13.\fi

\M{16}Declaration of local variables of the \PB{\\{main}} program.
In \CWEB\ one has the option of adding variables along the program, for example
by locally adding temporary variables related to a given sub-block of code.
However, the philosophy in the \sgfilter\ program is to keep all variables of
the \PB{\\{main}} section collected together, so as to simplify tasks as, for
example,
tracking down a given variable type definition.
The local variables of the program are as follows:
\medskip

\varitem[\PB{${*}\|x$}, \PB{${*}\\{yr}$}, \PB{${*}\\{yf}$}]{Pointers to the
double precision vectors keeping
the abscissa, unfiltered (raw) ordinata, and the and the resulting filtered
ordinata, respectively.}
\varitem[\PB{\\{mm}}]{Keeps track of the number of samples to analyze, $\PB{%
\\{mm}}\equiv M$.}
\varitem[\PB{${*}\\{file}$}]{Dummy file pointer used for scanning through input
data and
for writing data to an output file.}
\varitem[\PB{\\{input\_filename}}]{String for keeping the file name of the
input data.}
\varitem[\PB{\\{output\_filename}}]{Ditto for the output data.}
\varitem[\PB{\\{verbose}}]{Determines whether the program should run in verbose
mode
(logging various activities along the execution) or not. Default is off.}

\Y\B\4\X16:Definition of variables\X${}\E{}$\6
\&{int} \\{no\_arg};\6
\&{int} \\{nl}${}\K\.{DEFAULT\_NL};{}$\6
\&{int} \\{nr}${}\K\.{DEFAULT\_NR};{}$\6
\&{int} \\{ld}${}\K\.{DEFAULT\_LD};{}$\6
\&{int} \|m${}\K\.{DEFAULT\_M};{}$\6
\&{long} \&{int} \|k${},{}$ \\{mm}${}\K\T{0};{}$\6
\&{double} ${}{*}\|x,{}$ ${}{*}\\{yr},{}$ ${}{*}\\{yf};{}$\6
\&{char} \\{input\_filename}[\.{NCHMAX}]${}\K\.{""},{}$ \\{output\_filename}[%
\.{NCHMAX}]${}\K\.{""};{}$\6
\&{char} \\{verbose}${}\K\T{0};{}$\6
\&{FILE} ${}{*}\\{file}{}$;\par
\U13.\fi

\M{17}Parsing command line options. All input parameters are passed to the
program through command line options to the \sgfilter\ program.
The syntax of the accepted command line options is listed whenever the
program is invoked without any options, or whenever any of the \.{--help}
or \.{-h} options are specified at startup.

\Y\B\4\X17:Parse command line for options and parameters\X${}\E{}$\6
$\\{progname}\K\\{strip\_away\_path}(\\{argv}[\T{0}]);{}$\6
${}\\{no\_arg}\K\\{argc};{}$\6
\&{while} ${}(\MM\\{argc}){}$\5
${}\{{}$\1\6
\&{if} ${}(\R\\{strcmp}(\\{argv}[\\{no\_arg}-\\{argc}],\39\.{"-o"})\V\R%
\\{strcmp}(\\{argv}[\\{no\_arg}-\\{argc}],\39\.{"--outputfile"})){}$\5
${}\{{}$\1\6
${}\MM\\{argc};{}$\6
${}\\{strcpy}(\\{output\_filename},\39\\{argv}[\\{no\_arg}-\\{argc}]);{}$\6
\4${}\}{}$\2\6
\&{else} \&{if} ${}(\R\\{strcmp}(\\{argv}[\\{no\_arg}-\\{argc}],\39\.{"-i"})\V%
\R\\{strcmp}(\\{argv}[\\{no\_arg}-\\{argc}],\39\.{"--inputfile"})){}$\5
${}\{{}$\1\6
${}\MM\\{argc};{}$\6
${}\\{strcpy}(\\{input\_filename},\39\\{argv}[\\{no\_arg}-\\{argc}]);{}$\6
\4${}\}{}$\2\6
\&{else} \&{if} ${}(\R\\{strcmp}(\\{argv}[\\{no\_arg}-\\{argc}],\39\.{"-h"})\V%
\R\\{strcmp}(\\{argv}[\\{no\_arg}-\\{argc}],\39\.{"--help"})){}$\5
${}\{{}$\1\6
\\{showsomehelp}(\,);\6
\\{exit}(\T{0});\6
\4${}\}{}$\2\6
\&{else} \&{if} ${}(\R\\{strcmp}(\\{argv}[\\{no\_arg}-\\{argc}],\39\.{"-v"})\V%
\R\\{strcmp}(\\{argv}[\\{no\_arg}-\\{argc}],\39\.{"--verbose"})){}$\5
${}\{{}$\1\6
${}\\{verbose}\K(\\{verbose}\?\T{0}:\T{1});{}$\6
\4${}\}{}$\2\6
\&{else} \&{if} ${}(\R\\{strcmp}(\\{argv}[\\{no\_arg}-\\{argc}],\39%
\.{"-nl"})){}$\5
${}\{{}$\1\6
${}\MM\\{argc};{}$\6
\&{if} ${}(\R\\{sscanf}(\\{argv}[\\{no\_arg}-\\{argc}],\39\.{"\%d"},\39{\AND}%
\\{nl})){}$\5
${}\{{}$\1\6
\\{log}(\.{"Error\ in\ '-nl'\ opti}\)\.{on."});\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\&{else} \&{if} ${}(\R\\{strcmp}(\\{argv}[\\{no\_arg}-\\{argc}],\39%
\.{"-nr"})){}$\5
${}\{{}$\1\6
${}\MM\\{argc};{}$\6
\&{if} ${}(\R\\{sscanf}(\\{argv}[\\{no\_arg}-\\{argc}],\39\.{"\%d"},\39{\AND}%
\\{nr})){}$\5
${}\{{}$\1\6
\\{log}(\.{"Error\ in\ '-nr'\ opti}\)\.{on."});\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\&{else} \&{if} ${}(\R\\{strcmp}(\\{argv}[\\{no\_arg}-\\{argc}],\39%
\.{"-ld"})){}$\5
${}\{{}$\1\6
${}\MM\\{argc};{}$\6
\&{if} ${}(\R\\{sscanf}(\\{argv}[\\{no\_arg}-\\{argc}],\39\.{"\%d"},\39{\AND}%
\\{ld})){}$\5
${}\{{}$\1\6
\\{log}(\.{"Error\ in\ '-ld'\ opti}\)\.{on."});\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\&{else} \&{if} ${}(\R\\{strcmp}(\\{argv}[\\{no\_arg}-\\{argc}],\39%
\.{"-m"})){}$\5
${}\{{}$\1\6
${}\MM\\{argc};{}$\6
\&{if} ${}(\R\\{sscanf}(\\{argv}[\\{no\_arg}-\\{argc}],\39\.{"\%d"},\39{\AND}%
\|m)){}$\5
${}\{{}$\1\6
\\{log}(\.{"Error\ in\ '-m'\ optio}\)\.{n."});\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\&{else}\5
${}\{{}$\1\6
${}\\{log}(\.{"Unrecognized\ option}\)\.{\ '\%s'."},\39\\{argv}[\\{no\_arg}-%
\\{argc}]);{}$\6
\\{showsomehelp}(\,);\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\&{if} (\\{verbose})\1\5
${}\\{fprintf}(\\{stdout},\39\.{"This\ is\ \%s\ v.\%s.\ \%s}\)\.{\\n"},\39%
\\{progname},\39\.{VERSION},\39\.{COPYRIGHT}){}$;\2\par
\U13.\fi

\M{18}This is the where the raw (unfiltered) data is loaded into the computer
memory. This block assumes that the number of data points, $M$, has {\sl not}
previously been determined, neither by analysis of the input file nor
explicitly stated via command line options, and hence the number of samples
is automatically extracted using the \PB{\\{num\_coordinate\_pairs}} routine.

\Y\B\4\X18:Allocate memory and read \PB{\|M} samples of unfiltered data from
file\X${}\E{}$\6
\&{if} ${}(\R\\{strcmp}(\\{input\_filename},\39\.{""})){}$\5
${}\{{}$\1\6
\\{log}(\.{"No\ input\ file\ speci}\)\.{fied!\ (Please\ use\ th}\)\.{e\
'--inputfile'\ opti}\)\.{on.)"});\6
${}\\{log}(\.{"Execute\ '\%s\ --help'}\)\.{\ for\ help."},\39\\{progname});{}$\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
\&{if} ${}((\\{file}\K\\{fopen}(\\{input\_filename},\39\.{"r"}))\E\NULL){}$\5
${}\{{}$\1\6
${}\\{log}(\.{"Could\ not\ open\ \%s\ f}\)\.{or\ loading\ raw\ data!}\)\.{"},%
\39\\{input\_filename});{}$\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
${}\\{mm}\K\\{num\_coordinate\_pairs}(\\{file});{}$\6
\&{if} ${}(\\{mm}<\\{nl}+\\{nr}+\T{1}){}$\5
${}\{{}$\1\6
${}\\{log}(\.{"Error:\ The\ number\ M}\)\.{=\%ld\ of\ data\ points\ }\)\.{must\
be\ at\ least\ nl+}\)\.{nr+1=\%d"},\39\\{mm},\39\\{nl}+\\{nr}+\T{1});{}$\6
\\{log}(\.{"Please\ check\ your\ -}\)\.{nl\ or\ -nr\ options."});\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
\&{if} (\\{verbose})\5
${}\{{}$\1\6
${}\\{log}(\.{"Loading\ \%ld\ unfilte}\)\.{red\ samples\ from\ \%s.}\)\.{.."},%
\39\\{mm},\39\\{input\_filename});{}$\6
\\{log}(\.{"\ ...\ allocating\ mem}\)\.{ory\ for\ storage\ ..."});\6
\4${}\}{}$\2\6
${}\|x\K\\{dvector}(\T{1},\39\\{mm});{}$\6
${}\\{yr}\K\\{dvector}(\T{1},\39\\{mm});{}$\6
\8\#\&{if} \.{CONVOLVE\_WITH\_NR\_CONVLV}\6
${}\\{yf}\K\\{dvector}(\T{1},\39\T{2}*\\{mm});{}$\6
\8\#\&{else}\6
${}\\{yf}\K\\{dvector}(\T{1},\39\\{mm});{}$\6
\8\#\&{endif}\6
\&{if} (\\{verbose})\1\5
${}\\{log}(\.{"\ ...\ scanning\ \%s\ fo}\)\.{r\ input\ data\ ..."},\39\\{input%
\_filename});{}$\2\6
\&{for} ${}(\|k\K\T{1};{}$ ${}\|k\Z\\{mm};{}$ ${}\|k\PP){}$\5
${}\{{}$\1\6
${}\\{fscanf}(\\{file},\39\.{"\%lf"},\39{\AND}\|x[\|k]){}$;\C{ Scan
$x$-coordinate }\6
${}\\{fscanf}(\\{file},\39\.{"\%lf"},\39{\AND}\\{yr}[\|k]){}$;\C{ Scan
unfiltered $y$-coordinate }\6
\4${}\}{}$\2\6
\\{fclose}(\\{file});\6
\&{if} (\\{verbose})\1\5
\\{log}(\.{"\ ...\ done.\ Input\ no}\)\.{w\ residing\ in\ RAM."});\2\par
\U13.\fi

\M{19}Filter data. This is simple. One single call to the \PB{\\{sgfilter}}
routine and
we are done.

\Y\B\4\X19:Filter raw data through the Savitzky--Golay smoothing filter\X${}%
\E{}$\6
\&{if} ${}(\R\\{sgfilter}(\\{yr},\39\\{yf},\39\\{mm},\39\\{nl},\39\\{nr},\39%
\\{ld},\39\|m)){}$\5
${}\{{}$\1\6
\&{if} (\\{verbose})\1\5
\\{log}(\.{"Successfully\ perfor}\)\.{med\ Savitzky-Golay\ f}\)\.{iltering."});%
\2\6
\4${}\}{}$\2\6
\&{else}\5
${}\{{}$\1\6
\&{if} (\\{verbose})\1\5
\\{log}(\.{"Error:\ Could\ not\ pe}\)\.{rform\ Savitzky-Golay}\)\.{\
filtering."});\2\6
\4${}\}{}$\2\par
\U13.\fi

\M{20}Write the filtered data to file or \PB{\\{stdout}}, depending on whether
or not the
command line options \.{-o} or \.{-outputfile} were present when starting the
\sgfilter\ program. We here use a redirection of the \PB{\\{stdout}} stream
using
\PB{$\\{freopen}(\\{output\_filename},\.{"w"},\\{stdout})$ ) $\E$ $\NULL$ )}
and (in the case of unix-like
systems) a re-redirection back to terminal output again with
\PB{$\\{freopen}(\.{"/dev/tty"},\.{"a"},\\{stdout})$}.

\Y\B\4\X20:Write filtered data to file or terminal output\X${}\E{}$\6
\&{if} ${}(\R\\{strcmp}(\\{output\_filename},\39\.{""})){}$\5
${}\{{}$\C{ No filename specified }\1\6
\&{if} (\\{verbose})\1\5
${}\\{log}(\.{"Writing\ \%ld\ filtere}\)\.{d\ samples\ to\ console}\)\.{..."},%
\39\\{mm});{}$\2\6
\4${}\}{}$\2\6
\&{else}\5
${}\{{}$\C{ If file name specified $\Rightarrow$ redirect \PB{\\{stdout}} to
file }\1\6
\&{if} (\\{verbose})\1\5
${}\\{log}(\.{"Writing\ \%ld\ filtere}\)\.{d\ samples\ to\ \%s..."},\39\\{mm},%
\39\\{output\_filename});{}$\2\6
\&{if} ${}((\\{file}\K\\{freopen}(\\{output\_filename},\39\.{"w"},\39%
\\{stdout}))\E\NULL){}$\5
${}\{{}$\1\6
${}\\{log}(\.{"Error:\ Unable\ to\ re}\)\.{direct\ stdout\ stream}\)\.{\ to\
file\ \%s."},\39\\{output\_filename});{}$\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\&{for} ${}(\|k\K\T{1};{}$ ${}\|k\Z\\{mm};{}$ ${}\|k\PP){}$\1\5
${}\\{fprintf}(\\{stdout},\39\.{"\%1.8f\ \%1.8f\\n"},\39\|x[\|k],\39\\{yf}[%
\|k]);{}$\2\6
\8\#\&{ifdef} \.{UNIX\_LIKE\_OS}\6
${}\\{freopen}(\.{"/dev/tty"},\39\.{"a"},\39\\{stdout}){}$;\C{ Redirect \PB{%
\\{stdout}} back to console output }\6
\8\#\&{endif}\6
\&{if} (\\{verbose})\1\5
\\{log}(\.{"\ ...\ done."});\2\par
\U13.\fi

\M{21}Deallocate memory.

\Y\B\4\X21:Deallocate memory\X${}\E{}$\6
$\\{free\_dvector}(\|x,\39\T{1},\39\\{mm});{}$\6
${}\\{free\_dvector}(\\{yr},\39\T{1},\39\\{mm});{}$\6
\8\#\&{if} \.{CONVOLVE\_WITH\_NR\_CONVLV}\6
${}\\{free\_dvector}(\\{yf},\39\T{1},\39\T{2}*\\{mm});{}$\6
\8\#\&{else}\6
${}\\{free\_dvector}(\\{yf},\39\T{1},\39\\{mm});{}$\6
\8\#\&{endif}\par
\U13.\fi

\N{1}{22}Routines used by the program.

\Y\B\4\X22:Definitions of routines\X${}\E{}$\6
\X23:Routine for error messaging\X\6
\X24:Routine for allocation of integer precision vectors\X\6
\X25:Routine for allocation of double floating-point precision vectors\X\6
\X26:Routine for allocation of double floating-point precision matrices\X\6
\X27:Routine for deallocation of integer precision vectors\X\6
\X28:Routine for deallocation of double floating-point precision vectors\X\6
\X29:Routine for deallocation of double floating-point precision matrices\X\6
\X30:Routine for solving systems of linear equations by LU decomposition\X\6
\X31:Routine for performing LU decomposition of a matrix\X\6
\X32:Routine for discrete Fourier transformation of real-valued data\X\6
\X33:Routine for simultaneous fast Fourier transformation of two data sets\X\6
\X34:Routine for Fourier transformation of real-valued data\X\6
\X35:Routine for numerical convolution\X\6
\X36:Routine for computation of coefficients for Savitzky--Golay filtering\X\6
\X37:Routine for Savitzky--Golay filtering\X\6
\X38:Routine for removing preceding path of filenames\X\6
\X40:Routine for displaying a brief help message on usage\X\6
\X42:Routine for obtaining the number of coordinate pairs in a file\X\par
\U13.\fi

\M{23}The \PB{\&{void} \\{log\_printf}(\&{const} \&{char} ${}{*}\\{function%
\_name},{}$\&{const} \&{char} ${}{*}\\{format},\,\ldots\,)$}
routine writes formatted entries to standard output, displaying time and
calling routine in a coherent manner. Notice that although the \PB{\\{log%
\_printf}(\,)}
routine is the one which performs the actual messaging, the \PB{\\{log}(\,)}
macro
(defined in the header file) is the preferred way of accessing this routine,
as it provides a more compact notation and automatically takes care of
supplying
the reference to the name of the calling function.

Also notice that the \PB{\&{const} \&{char}} type of the last two input pointer
arguments
here is absolutely essential in order to pass strict pedantic compilation with
\GCC.

The routine accepts two input parameters. First, \PB{\\{function\_name}} which
should
be the name of the calling function. This is to ensure that any displayed
error messages are properly matched to the issuing routines. Notice, however,
that the \PB{\\{log}(\,)} macro (which is the preferred way of displaying error
messages)
automatically takes care of supplying the proper function name.
Second, \PB{\\{format}}, which simply is the format and message string to be
displayed, formatted in the \CEE-standard \PB{\\{printf}(\,)} or \PB{%
\\{fprintf}(\,)} syntax.

\Y\B\4\X23:Routine for error messaging\X${}\E{}$\6
\&{void} \\{log\_printf}(\&{const} \&{char} ${}{*}\\{function\_name},\39{}$%
\&{const} \&{char} ${}{*}\\{format},\39\,\ldots\,){}$\1\1\2\2\6
${}\{{}$\1\6
\&{va\_list} \\{args};\6
\&{time\_t} \\{time0};\6
\&{struct} \\{tm} \\{lt};\6
\&{struct} \\{timeval} \\{tv};\6
\&{char} \\{logentry}[\T{1024}];\7
${}\\{gettimeofday}({\AND}\\{tv},\39\NULL);{}$\6
${}\\{time}({\AND}\\{time0});{}$\6
${}\\{lt}\K{*}\\{localtime}({\AND}\\{time0});{}$\6
${}\\{sprintf}(\\{logentry},\39\.{"\%02u\%02u\%02u\ \%02u:\%}\)\.{02u:\%02u.%
\%03d\ "},\39\\{lt}.\\{tm\_year}-\T{100},\39\\{lt}.\\{tm\_mon}+\T{1},\39\\{lt}.%
\\{tm\_mday},\39\\{lt}.\\{tm\_hour},\39\\{lt}.\\{tm\_min},\39\\{lt}.\\{tm%
\_sec},\39\\{tv}.\\{tv\_usec}/\T{1000});{}$\6
${}\\{sprintf}(\\{logentry}+\\{strlen}(\\{logentry}),\39\.{"(\%s)\ "},\39%
\\{function\_name});{}$\6
${}\\{va\_start}(\\{args},\39\\{format}){}$;\C{ Initialize args by the \PB{%
\\{va\_start}(\,)} macro }\6
${}\\{vsprintf}(\\{logentry}+\\{strlen}(\\{logentry}),\39\\{format},\39%
\\{args});{}$\6
\\{va\_end}(\\{args});\C{ Terminate the use of args by the \PB{\\{va\_end}(\,)}
macro }\6
${}\\{sprintf}(\\{logentry}+\\{strlen}(\\{logentry}),\39\.{"\\n"}){}$;\C{
Always append newline }\6
${}\\{fprintf}(\\{stdout},\39\.{"\%s"},\39\\{logentry});{}$\6
\&{return};\6
\4${}\}{}$\2\par
\U22.\fi

\M{24}The \PB{\&{int} ${}{*}{}$\\{ivector}(\&{long} \\{nl}${},{}$\&{long} %
\\{nh})} routine allocates a real-valued vector
of integer precision, with vector index ranging from \PB{\\{nl}} to \PB{%
\\{nh}}.

\Y\B\4\X24:Routine for allocation of integer precision vectors\X${}\E{}$\6
\&{int} ${}{*}{}$\\{ivector}(\&{long} \\{nl}${},\39{}$\&{long} \\{nh})\1\1\2\2\6
${}\{{}$\1\6
\&{int} ${}{*}\|v;{}$\7
${}\|v\K{}$(\&{int} ${}{*}){}$ \\{malloc}${}((\&{size\_t})((\\{nh}-\\{nl}+%
\T{2})*\&{sizeof}(\&{int})));{}$\6
\&{if} ${}(\R\|v){}$\5
${}\{{}$\1\6
\\{log}(\.{"Error:\ Allocation\ f}\)\.{ailure."});\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
\&{return} \|v${}-\\{nl}+\T{1};{}$\6
\4${}\}{}$\2\par
\U22.\fi

\M{25}The \PB{\&{double} ${}{*}{}$\\{dvector}(\&{long} \\{nl}${},{}$\&{long} %
\\{nh})} routine allocates a real-valued
vector of double precision, with vector index ranging from \PB{\\{nl}} to \PB{%
\\{nh}}.

\Y\B\4\X25:Routine for allocation of double floating-point precision vectors%
\X${}\E{}$\6
\&{double} ${}{*}{}$\\{dvector}(\&{long} \\{nl}${},\39{}$\&{long} \\{nh})\1\1\2%
\2\6
${}\{{}$\1\6
\&{double} ${}{*}\|v;{}$\6
\&{long} \|k;\7
${}\|v\K{}$(\&{double} ${}{*}){}$ \\{malloc}${}((\&{size\_t})((\\{nh}-\\{nl}+%
\T{2})*\&{sizeof}(\&{double})));{}$\6
\&{if} ${}(\R\|v){}$\5
${}\{{}$\1\6
\\{log}(\.{"Error:\ Allocation\ f}\)\.{ailure."});\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
\&{for} ${}(\|k\K\\{nl};{}$ ${}\|k\Z\\{nh};{}$ ${}\|k\PP){}$\1\5
${}\|v[\|k]\K\T{0.0};{}$\2\6
\&{return} \|v${}-\\{nl}+\T{1};{}$\6
\4${}\}{}$\2\par
\U22.\fi

\M{26}The \PB{\&{double} ${}{*}{*}{}$\\{dmatrix}(\&{long} \\{nrl}${},{}$%
\&{long} \\{nrh}${},{}$\&{long} \\{ncl}${},{}$\&{long} \\{nch})} routine
allocates an array of double floating-point precision, with row index
ranging from \PB{\\{nrl}} to \PB{\\{nrh}} and column index ranging from \PB{%
\\{ncl}} to \PB{\\{nch}}.

\Y\B\4\X26:Routine for allocation of double floating-point precision matrices%
\X${}\E{}$\6
\&{double} ${}{*}{*}{}$\\{dmatrix}(\&{long} \\{nrl}${},\39{}$\&{long} %
\\{nrh}${},\39{}$\&{long} \\{ncl}${},\39{}$\&{long} \\{nch})\1\1\2\2\6
${}\{{}$\1\6
\&{long} \|i${},{}$ \\{nrow}${}\K\\{nrh}-\\{nrl}+\T{1},{}$ \\{ncol}${}\K%
\\{nch}-\\{ncl}+\T{1};{}$\6
\&{double} ${}{*}{*}\|m;{}$\7
${}\|m\K{}$(\&{double} ${}{*}{*}){}$ \\{malloc}${}((\&{size\_t})((\\{nrow}+%
\T{1})*{}$\&{sizeof}(\&{double} ${}{*})));{}$\6
\&{if} ${}(\R\|m){}$\5
${}\{{}$\1\6
\\{log}(\.{"Allocation\ failure\ }\)\.{1\ occurred."});\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
${}\|m\MRL{+{\K}}\T{1};{}$\6
${}\|m\MRL{-{\K}}\\{nrl};{}$\6
${}\|m[\\{nrl}]\K{}$(\&{double} ${}{*}){}$ \\{malloc}${}((\&{size\_t})((%
\\{nrow}*\\{ncol}+\T{1})*\&{sizeof}(\&{double})));{}$\6
\&{if} ${}(\R\|m[\\{nrl}]){}$\5
${}\{{}$\1\6
\\{log}(\.{"Allocation\ failure\ }\)\.{2\ occurred."});\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
${}\|m[\\{nrl}]\MRL{+{\K}}\T{1};{}$\6
${}\|m[\\{nrl}]\MRL{-{\K}}\\{ncl};{}$\6
\&{for} ${}(\|i\K\\{nrl}+\T{1};{}$ ${}\|i\Z\\{nrh};{}$ ${}\|i\PP){}$\1\5
${}\|m[\|i]\K\|m[\|i-\T{1}]+\\{ncol};{}$\2\6
\&{return} \|m;\6
\4${}\}{}$\2\par
\U22.\fi

\M{27}The \PB{\&{void} \\{free\_ivector}(\&{int} ${}{*}\|v,{}$\&{long} %
\\{nl}${},{}$\&{long} \\{nh})} routine release the
memory occupied by the real-valued vector \PB{\|v [ \\{nl} $\,\ldots\,{}$ %
\\{nh} ]}.

\Y\B\4\X27:Routine for deallocation of integer precision vectors\X${}\E{}$\6
\&{void} \\{free\_ivector}(\&{int} ${}{*}\|v,\39{}$\&{long} \\{nl}${},\39{}$%
\&{long} \\{nh})\1\1\2\2\6
${}\{{}$\1\6
\\{free}((\&{char} ${}{*})(\|v+\\{nl}-\T{1}));{}$\6
\4${}\}{}$\2\par
\U22.\fi

\M{28}The \PB{\\{free\_dvector}} routine release the memory occupied by the
real-valued vector \PB{\|v [ \\{nl} $\,\ldots\,{}$ \\{nh} ]}.

\Y\B\4\X28:Routine for deallocation of double floating-point precision vectors%
\X${}\E{}$\6
\&{void} \\{free\_dvector}(\&{double} ${}{*}\|v,\39{}$\&{long} \\{nl}${},\39{}$%
\&{long} \\{nh})\1\1\2\2\6
${}\{{}$\1\6
\\{free}((\&{char} ${}{*})(\|v+\\{nl}-\T{1}));{}$\6
\4${}\}{}$\2\par
\U22.\fi

\M{29}The \PB{\&{void} \\{free\_dmatrix}(\&{double} ${}{*}{*}\|m,{}$\&{long} %
\\{nrl}${},{}$\&{long} \\{nrh}${},{}$\&{long} \\{ncl}${},{}$\&{long} \\{nch})}
routine releases the memory occupied by the double floating-point precision
matrix \PB{\|v [ \\{nl} $\,\ldots\,{}$ \\{nh} ]}, as allocated by \PB{%
\\{dmatrix}(\,)}.

\Y\B\4\X29:Routine for deallocation of double floating-point precision matrices%
\X${}\E{}$\6
\&{void} \\{free\_dmatrix}(\&{double} ${}{*}{*}\|m,\39{}$\&{long} \\{nrl}${},%
\39{}$\&{long} \\{nrh}${},\39{}$\&{long} \\{ncl}${},\39{}$\&{long} \\{nch})\1\1%
\2\2\6
${}\{{}$\1\6
\\{free}((\&{char} ${}{*})(\|m[\\{nrl}]+\\{ncl}-\T{1}));{}$\6
\\{free}((\&{char} ${}{*})(\|m+\\{nrl}-\T{1}));{}$\6
\4${}\}{}$\2\par
\U22.\fi

\M{30}The \PB{\\{lubksb}(\&{double} ${}{*}{*}\|a,{}$\&{int} \|n${},{}$\&{int}
${}{*}\\{indx},{}$\&{double} \|b[\,])} routine solves the set
of \PB{\|n} linear equations ${\bf A}\cdot{\bf x}={\bf b}$ where ${\bf A}$ is a
real-valued $[n\times n]$-matrix and ${\bf x}$ and ${\bf b}$ are real-valued
$[n\times1]$-vectors. Here \PB{\|a[\T{1...}\|n][\T{1...}\|n]} is input, however
{\sl not} as the
matrix ${\bf A}$ but rather as its corresponding LU decomposition as determined
by the \PB{\\{ludcmp}} routine. Here \PB{\\{indx}[\T{1...}\|n]} is input as the
permutation vector
returned by \PB{\\{ludcmp}}, \PB{\|b[\T{1...}\|n]} is input as the right-hand
side vector
${\bf b}$, and returns with the solution vector ${\bf x}$.
The parameters \PB{\|a}, \PB{\|n}, and \PB{\\{indx}} are not modified by this
routine and
can be left in place for successive calls with different right-hand sides
${\bf b}$. This routine takes into account the possibility that ${\bf b}$
will begin with many zero elements, so it is efficient for use in matrix
inversion.
The \PB{\\{lubksb}} routine is adopted from {\sl Numerical Recipes in C}, 2nd
Edn
(Cambridge University Press, New York, 1994).

\Y\B\4\X30:Routine for solving systems of linear equations by LU decomposition%
\X${}\E{}$\6
\&{void} \\{lubksb}(\&{double} ${}{*}{*}\|a,\39{}$\&{int} \|n${},\39{}$\&{int}
${}{*}\\{indx},\39{}$\&{double} \|b[\,])\1\1\2\2\6
${}\{{}$\1\6
\&{int} \|i${},{}$ \\{ii}${}\K\T{0},{}$ \\{ip}${},{}$ \|j;\6
\&{double} \\{sum};\7
\&{for} ${}(\|i\K\T{1};{}$ ${}\|i\Z\|n;{}$ ${}\|i\PP){}$\5
${}\{{}$\1\6
${}\\{ip}\K\\{indx}[\|i];{}$\6
${}\\{sum}\K\|b[\\{ip}];{}$\6
${}\|b[\\{ip}]\K\|b[\|i];{}$\6
\&{if} (\\{ii})\1\6
\&{for} ${}(\|j\K\\{ii};{}$ ${}\|j\Z\|i-\T{1};{}$ ${}\|j\PP){}$\1\5
${}\\{sum}\MRL{-{\K}}\|a[\|i][\|j]*\|b[\|j];{}$\2\2\6
\&{else} \&{if} (\\{sum})\1\5
${}\\{ii}\K\|i;{}$\2\6
${}\|b[\|i]\K\\{sum};{}$\6
\4${}\}{}$\2\6
\&{for} ${}(\|i\K\|n;{}$ ${}\|i\G\T{1};{}$ ${}\|i\MM){}$\5
${}\{{}$\1\6
${}\\{sum}\K\|b[\|i];{}$\6
\&{for} ${}(\|j\K\|i+\T{1};{}$ ${}\|j\Z\|n;{}$ ${}\|j\PP){}$\1\5
${}\\{sum}\MRL{-{\K}}\|a[\|i][\|j]*\|b[\|j];{}$\2\6
${}\|b[\|i]\K\\{sum}/\|a[\|i][\|i];{}$\6
\4${}\}{}$\2\6
\4${}\}{}$\2\par
\U22.\fi

\M{31}Given a square and real-valued matrix \PB{\|a[\T{1...}\|n][\T{1...}\|n]},
the
\PB{\\{ludcmp}(\&{float} ${}{*}{*}\|a,{}$\&{int} \|n${},{}$\&{int} ${}{*}%
\\{indx},{}$\&{float} ${}{*}\|d)$} routine replaces it by the
corresponding LU decomposition of a rowwise permutation
of itself. Entering the routine, the square matrix \PB{\|a} and its number of
columns (or rows) \PB{\|n} are inputs. On return, \PB{\|a} is arranged as in
Eq.~(2.3.14)
of {\sl Numerical Recipes in C}, 2nd edition, while \PB{\\{indx}[\T{1...}\|n]}
is an output
vector that records the row permutation effected by the partial pivoting, and
\PB{\|d} is output as $\pm1$ depending on whether the number of row
interchanges
was even or odd, respectively. This routine is commonly used in combination
with \PB{\\{lubksb}} to solve linear equations or invert a matrix.
The \PB{\\{ludcmp}} routine is adopted from {\sl Numerical Recipes in C}, 2nd
Edn
(Cambridge University Press, New York, 1994).

\Y\B\4\X31:Routine for performing LU decomposition of a matrix\X${}\E{}$\6
\&{void} \\{ludcmp}(\&{double} ${}{*}{*}\|a,\39{}$\&{int} \|n${},\39{}$\&{int}
${}{*}\\{indx},\39{}$\&{double} ${}{*}\|d){}$\1\1\2\2\6
${}\{{}$\1\6
\&{int} \|i${},{}$ \\{imax}${}\K\T{0},{}$ \|j${},{}$ \|k;\6
\&{double} \\{big}${},{}$ \\{dum}${},{}$ \\{sum}${},{}$ \\{temp};\6
\&{double} ${}{*}\\{vv};{}$\7
${}\\{vv}\K\\{dvector}(\T{1},\39\|n);{}$\6
${}{*}\|d\K\T{1.0};{}$\6
\&{for} ${}(\|i\K\T{1};{}$ ${}\|i\Z\|n;{}$ ${}\|i\PP){}$\5
${}\{{}$\1\6
${}\\{big}\K\T{0.0};{}$\6
\&{for} ${}(\|j\K\T{1};{}$ ${}\|j\Z\|n;{}$ ${}\|j\PP){}$\1\6
\&{if} ${}((\\{temp}\K\\{fabs}(\|a[\|i][\|j]))>\\{big}){}$\1\5
${}\\{big}\K\\{temp};{}$\2\2\6
\&{if} ${}(\\{big}\E\T{0.0}){}$\5
${}\{{}$\1\6
\\{log}(\.{"Error:\ Singular\ mat}\)\.{rix\ found\ in\ routine}\)\.{\
ludcmp()"});\6
\\{exit}(\T{1});\6
\4${}\}{}$\2\6
${}\\{vv}[\|i]\K\T{1.0}/\\{big};{}$\6
\4${}\}{}$\2\6
\&{for} ${}(\|j\K\T{1};{}$ ${}\|j\Z\|n;{}$ ${}\|j\PP){}$\5
${}\{{}$\1\6
\&{for} ${}(\|i\K\T{1};{}$ ${}\|i<\|j;{}$ ${}\|i\PP){}$\5
${}\{{}$\1\6
${}\\{sum}\K\|a[\|i][\|j];{}$\6
\&{for} ${}(\|k\K\T{1};{}$ ${}\|k<\|i;{}$ ${}\|k\PP){}$\1\5
${}\\{sum}\MRL{-{\K}}\|a[\|i][\|k]*\|a[\|k][\|j];{}$\2\6
${}\|a[\|i][\|j]\K\\{sum};{}$\6
\4${}\}{}$\2\6
${}\\{big}\K\T{0.0};{}$\6
\&{for} ${}(\|i\K\|j;{}$ ${}\|i\Z\|n;{}$ ${}\|i\PP){}$\5
${}\{{}$\1\6
${}\\{sum}\K\|a[\|i][\|j];{}$\6
\&{for} ${}(\|k\K\T{1};{}$ ${}\|k<\|j;{}$ ${}\|k\PP){}$\1\5
${}\\{sum}\MRL{-{\K}}\|a[\|i][\|k]*\|a[\|k][\|j];{}$\2\6
${}\|a[\|i][\|j]\K\\{sum};{}$\6
\&{if} ${}((\\{dum}\K\\{vv}[\|i]*\\{fabs}(\\{sum}))\G\\{big}){}$\5
${}\{{}$\1\6
${}\\{big}\K\\{dum};{}$\6
${}\\{imax}\K\|i;{}$\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\&{if} ${}(\|j\I\\{imax}){}$\5
${}\{{}$\1\6
\&{for} ${}(\|k\K\T{1};{}$ ${}\|k\Z\|n;{}$ ${}\|k\PP){}$\5
${}\{{}$\1\6
${}\\{dum}\K\|a[\\{imax}][\|k];{}$\6
${}\|a[\\{imax}][\|k]\K\|a[\|j][\|k];{}$\6
${}\|a[\|j][\|k]\K\\{dum};{}$\6
\4${}\}{}$\2\6
${}{*}\|d\K{-}({*}\|d);{}$\6
${}\\{vv}[\\{imax}]\K\\{vv}[\|j];{}$\6
\4${}\}{}$\2\6
${}\\{indx}[\|j]\K\\{imax};{}$\6
\&{if} ${}(\|a[\|j][\|j]\E\T{0.0}){}$\1\5
${}\|a[\|j][\|j]\K\.{EPSILON};{}$\2\6
\&{if} ${}(\|j\I\|n){}$\5
${}\{{}$\1\6
${}\\{dum}\K\T{1.0}/(\|a[\|j][\|j]);{}$\6
\&{for} ${}(\|i\K\|j+\T{1};{}$ ${}\|i\Z\|n;{}$ ${}\|i\PP){}$\1\5
${}\|a[\|i][\|j]\MRL{*{\K}}\\{dum};{}$\2\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
${}\\{free\_dvector}(\\{vv},\39\T{1},\39\|n);{}$\6
\4${}\}{}$\2\par
\U22.\fi

\M{32}The \PB{\\{four1}(\&{double} \\{data}[\,]${},{}$\&{unsigned} \&{long} %
\\{nn}${},{}$\&{int} \\{isign})} routine replaces
\PB{$\\{data}[\T{1...2}*\\{nn}]$} by its discrete Fourier transform, if \PB{%
\\{isign}} is input
as $+1$; or replaces \PB{$\\{data}[\T{1..2}*\\{nn}]$} by \PB{\\{nn}} times its
inverse discrete Fourier
transform, if \PB{\\{isign}} is input as $-1$. Here \PB{\\{data}} is a
complex-valued array
of length \PB{\\{nn}} or, equivalently, a real array of length \PB{$\T{2}*%
\\{nn}$}, wher \PB{\\{nn}}
{\sl must} be an integer power of 2 (this is not checked for).
The \PB{\\{four1}} routine is adopted from {\sl Numerical Recipes in C}, 2nd
Edn
(Cambridge University Press, New York, 1994).

\Y\B\4\X32:Routine for discrete Fourier transformation of real-valued data\X${}%
\E{}$\6
\8\#\&{include} \.{<math.h>}\6
\8\#\&{define} $\.{SWAP}(\|a,\39\|b)\\{tempr}\K(\|a);{}$\6
${}(\|a)\K(\|b);$ $(\|b)\K\\{tempr}$ \6
\&{void} \\{four1}(\&{double} \\{data}[\,]${},\39{}$\&{unsigned} \&{long} %
\\{nn}${},\39{}$\&{int} \\{isign})\1\1\2\2\6
${}\{{}$\1\6
\&{unsigned} \&{long} \|n${},{}$ \\{mmax}${},{}$ \|m${},{}$ \|j${},{}$ %
\\{istep}${},{}$ \|i;\6
\&{double} \\{wtemp}${},{}$ \\{wr}${},{}$ \\{wpr}${},{}$ \\{wpi}${},{}$ %
\\{wi}${},{}$ \\{theta};\6
\&{double} \\{tempr}${},{}$ \\{tempi};\7
${}\|n\K\\{nn}\LL\T{1};{}$\6
${}\|j\K\T{1};{}$\6
\&{for} ${}(\|i\K\T{1};{}$ ${}\|i<\|n;{}$ ${}\|i\MRL{+{\K}}\T{2}){}$\5
${}\{{}$\1\6
\&{if} ${}(\|j>\|i){}$\5
${}\{{}$\1\6
${}\.{SWAP}(\\{data}[\|j],\39\\{data}[\|i]);{}$\6
${}\.{SWAP}(\\{data}[\|j+\T{1}],\39\\{data}[\|i+\T{1}]);{}$\6
\4${}\}{}$\2\6
${}\|m\K\|n\GG\T{1};{}$\6
\&{while} ${}(\|m\G\T{2}\W\|j>\|m){}$\5
${}\{{}$\1\6
${}\|j\MRL{-{\K}}\|m;{}$\6
${}\|m\MRL{{\GG}{\K}}\T{1};{}$\6
\4${}\}{}$\2\6
${}\|j\MRL{+{\K}}\|m;{}$\6
\4${}\}{}$\2\6
${}\\{mmax}\K\T{2};{}$\6
\&{while} ${}(\|n>\\{mmax}){}$\5
${}\{{}$\1\6
${}\\{istep}\K\\{mmax}\LL\T{1};{}$\6
${}\\{theta}\K\\{isign}*(\T{6.28318530717959}/\\{mmax});{}$\6
${}\\{wtemp}\K\\{sin}(\T{0.5}*\\{theta});{}$\6
${}\\{wpr}\K{-}\T{2.0}*\\{wtemp}*\\{wtemp};{}$\6
${}\\{wpi}\K\\{sin}(\\{theta});{}$\6
${}\\{wr}\K\T{1.0};{}$\6
${}\\{wi}\K\T{0.0};{}$\6
\&{for} ${}(\|m\K\T{1};{}$ ${}\|m<\\{mmax};{}$ ${}\|m\MRL{+{\K}}\T{2}){}$\5
${}\{{}$\1\6
\&{for} ${}(\|i\K\|m;{}$ ${}\|i\Z\|n;{}$ ${}\|i\MRL{+{\K}}\\{istep}){}$\5
${}\{{}$\1\6
${}\|j\K\|i+\\{mmax};{}$\6
${}\\{tempr}\K\\{wr}*\\{data}[\|j]-\\{wi}*\\{data}[\|j+\T{1}];{}$\6
${}\\{tempi}\K\\{wr}*\\{data}[\|j+\T{1}]+\\{wi}*\\{data}[\|j];{}$\6
${}\\{data}[\|j]\K\\{data}[\|i]-\\{tempr};{}$\6
${}\\{data}[\|j+\T{1}]\K\\{data}[\|i+\T{1}]-\\{tempi};{}$\6
${}\\{data}[\|i]\MRL{+{\K}}\\{tempr};{}$\6
${}\\{data}[\|i+\T{1}]\MRL{+{\K}}\\{tempi};{}$\6
\4${}\}{}$\2\6
${}\\{wr}\K(\\{wtemp}\K\\{wr})*\\{wpr}-\\{wi}*\\{wpi}+\\{wr};{}$\6
${}\\{wi}\K\\{wi}*\\{wpr}+\\{wtemp}*\\{wpi}+\\{wi};{}$\6
\4${}\}{}$\2\6
${}\\{mmax}\K\\{istep};{}$\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\8\#\&{undef} \.{SWAP}\par
\U22.\fi

\M{33}The \PB{\\{twofft}(\&{double} \\{data1}[\,]${},{}$\&{double} \\{data2}[%
\,]${},{}$\&{double} \\{fft1}[\,]${},{}$\&{double} \\{fft2}[\,]${},{}$%
\&{unsigned} \&{long} \|n)} routine takes two real-valued arrays \PB{\\{data1}[%
\T{1...}\|n]}
and \PB{\\{data2}[\T{1...}\|n]} as input, makes a call to the \PB{\\{four1}}
routine and
returns two complex-valued output arrays \PB{$\\{fft1}[\T{1...2}*\|n]$}
and \PB{$\\{fft2}[\T{1...2}*\|n]$}, each of complex length \PB{\|n} (that is to
say, a real
length of \PB{$\T{2}*\|n$} elements), which contain the discrete Fourier
transforms
of the respective data arrays. Here \PB{\|n} {\sl must} be an integer power of
2.
The \PB{\\{twofft}} routine is adopted from {\sl Numerical Recipes in C}, 2nd
Edn
(Cambridge University Press, New York, 1994).

\Y\B\4\X33:Routine for simultaneous fast Fourier transformation of two data
sets\X${}\E{}$\6
\&{void} \\{twofft}(\&{double} \\{data1}[\,]${},\39{}$\&{double} \\{data2}[%
\,]${},\39{}$\&{double} \\{fft1}[\,]${},\39{}$\&{double} \\{fft2}[\,]${},\39{}$%
\&{unsigned} \&{long} \|n)\1\1\2\2\6
${}\{{}$\1\6
\&{void} \\{four1}(\&{double} \\{data}[\,]${},\39{}$\&{unsigned} \&{long} %
\\{nn}${},\39{}$\&{int} \\{isign});\6
\&{unsigned} \&{long} \\{nn3}${},{}$ \\{nn2}${},{}$ \\{jj}${},{}$ \|j;\6
\&{double} \\{rep}${},{}$ \\{rem}${},{}$ \\{aip}${},{}$ \\{aim};\7
${}\\{nn3}\K\T{1}+(\\{nn2}\K\T{2}+\|n+\|n);{}$\6
\&{for} ${}(\|j\K\T{1},\39\\{jj}\K\T{2};{}$ ${}\|j\Z\|n;{}$ ${}\|j\PP,\39\\{jj}%
\MRL{+{\K}}\T{2}){}$\5
${}\{{}$\1\6
${}\\{fft1}[\\{jj}-\T{1}]\K\\{data1}[\|j];{}$\6
${}\\{fft1}[\\{jj}]\K\\{data2}[\|j];{}$\6
\4${}\}{}$\2\6
${}\\{four1}(\\{fft1},\39\|n,\39\T{1});{}$\6
${}\\{fft2}[\T{1}]\K\\{fft1}[\T{2}];{}$\6
${}\\{fft1}[\T{2}]\K\\{fft2}[\T{2}]\K\T{0.0};{}$\6
\&{for} ${}(\|j\K\T{3};{}$ ${}\|j\Z\|n+\T{1};{}$ ${}\|j\MRL{+{\K}}\T{2}){}$\5
${}\{{}$\1\6
${}\\{rep}\K\T{0.5}*(\\{fft1}[\|j]+\\{fft1}[\\{nn2}-\|j]);{}$\6
${}\\{rem}\K\T{0.5}*(\\{fft1}[\|j]-\\{fft1}[\\{nn2}-\|j]);{}$\6
${}\\{aip}\K\T{0.5}*(\\{fft1}[\|j+\T{1}]+\\{fft1}[\\{nn3}-\|j]);{}$\6
${}\\{aim}\K\T{0.5}*(\\{fft1}[\|j+\T{1}]-\\{fft1}[\\{nn3}-\|j]);{}$\6
${}\\{fft1}[\|j]\K\\{rep};{}$\6
${}\\{fft1}[\|j+\T{1}]\K\\{aim};{}$\6
${}\\{fft1}[\\{nn2}-\|j]\K\\{rep};{}$\6
${}\\{fft1}[\\{nn3}-\|j]\K{-}\\{aim};{}$\6
${}\\{fft2}[\|j]\K\\{aip};{}$\6
${}\\{fft2}[\|j+\T{1}]\K{-}\\{rem};{}$\6
${}\\{fft2}[\\{nn2}-\|j]\K\\{aip};{}$\6
${}\\{fft2}[\\{nn3}-\|j]\K\\{rem};{}$\6
\4${}\}{}$\2\6
\4${}\}{}$\2\par
\U22.\fi

\M{34}The \PB{\\{realft}(\&{double} \\{data}[\,]${},{}$\&{unsigned} \&{long} %
\|n${},{}$\&{int} \\{isign})} routine
calculates the Fourier transform of a set of \PB{\|n} real-valued data points.
On return the routine replaces this data (which is stored in array
\PB{\\{data}[\T{1...}\|n]}) by the positive frequency half of its complex
Fourier
transform. The real-valued first and last components of the complex
transform are returned in elements \PB{\\{data}[\T{1}]} and \PB{\\{data}[%
\T{2}]}, respectively.
Here \PB{\|n} must be a power of 2. This routine also calculates the inverse
transform of a complex data array if it is the transform of real data.
(In this case, the result must be multiplied by \PB{$\T{2}/\|n$}.)
The \PB{\\{realft}} routine is adopted from {\sl Numerical Recipes in C}, 2nd
Edn
(Cambridge University Press, New York, 1994).

\Y\B\4\X34:Routine for Fourier transformation of real-valued data\X${}\E{}$\6
\&{void} \\{realft}(\&{double} \\{data}[\,]${},\39{}$\&{unsigned} \&{long} %
\|n${},\39{}$\&{int} \\{isign})\1\1\2\2\6
${}\{{}$\1\6
\&{void} \\{four1}(\&{double} \\{data}[\,]${},\39{}$\&{unsigned} \&{long} %
\\{nn}${},\39{}$\&{int} \\{isign});\6
\&{unsigned} \&{long} \|i${},{}$ \\{i1}${},{}$ \\{i2}${},{}$ \\{i3}${},{}$ %
\\{i4}${},{}$ \\{np3};\6
\&{double} \\{c1}${}\K\T{0.5},{}$ \\{c2}${},{}$ \\{h1r}${},{}$ \\{h1i}${},{}$ %
\\{h2r}${},{}$ \\{h2i};\6
\&{double} \\{wr}${},{}$ \\{wi}${},{}$ \\{wpr}${},{}$ \\{wpi}${},{}$ %
\\{wtemp}${},{}$ \\{theta};\7
${}\\{theta}\K\T{3.141592653589793}/(\&{double})(\|n\GG\T{1});{}$\6
\&{if} ${}(\\{isign}\E\T{1}){}$\5
${}\{{}$\1\6
${}\\{c2}\K{-}\T{0.5};{}$\6
${}\\{four1}(\\{data},\39\|n\GG\T{1},\39\T{1});{}$\6
\4${}\}{}$\2\6
\&{else}\5
${}\{{}$\1\6
${}\\{c2}\K\T{0.5};{}$\6
${}\\{theta}\K{-}\\{theta};{}$\6
\4${}\}{}$\2\6
${}\\{wtemp}\K\\{sin}(\T{0.5}*\\{theta});{}$\6
${}\\{wpr}\K{-}\T{2.0}*\\{wtemp}*\\{wtemp};{}$\6
${}\\{wpi}\K\\{sin}(\\{theta});{}$\6
${}\\{wr}\K\T{1.0}+\\{wpr};{}$\6
${}\\{wi}\K\\{wpi};{}$\6
${}\\{np3}\K\|n+\T{3};{}$\6
\&{for} ${}(\|i\K\T{2};{}$ ${}\|i\Z(\|n\GG\T{2});{}$ ${}\|i\PP){}$\5
${}\{{}$\1\6
${}\\{i4}\K\T{1}+(\\{i3}\K\\{np3}-(\\{i2}\K\T{1}+(\\{i1}\K\|i+\|i-\T{1})));{}$\6
${}\\{h1r}\K\\{c1}*(\\{data}[\\{i1}]+\\{data}[\\{i3}]);{}$\6
${}\\{h1i}\K\\{c1}*(\\{data}[\\{i2}]-\\{data}[\\{i4}]);{}$\6
${}\\{h2r}\K{-}\\{c2}*(\\{data}[\\{i2}]+\\{data}[\\{i4}]);{}$\6
${}\\{h2i}\K\\{c2}*(\\{data}[\\{i1}]-\\{data}[\\{i3}]);{}$\6
${}\\{data}[\\{i1}]\K\\{h1r}+\\{wr}*\\{h2r}-\\{wi}*\\{h2i};{}$\6
${}\\{data}[\\{i2}]\K\\{h1i}+\\{wr}*\\{h2i}+\\{wi}*\\{h2r};{}$\6
${}\\{data}[\\{i3}]\K\\{h1r}-\\{wr}*\\{h2r}+\\{wi}*\\{h2i};{}$\6
${}\\{data}[\\{i4}]\K{-}\\{h1i}+\\{wr}*\\{h2i}+\\{wi}*\\{h2r};{}$\6
${}\\{wr}\K(\\{wtemp}\K\\{wr})*\\{wpr}-\\{wi}*\\{wpi}+\\{wr};{}$\6
${}\\{wi}\K\\{wi}*\\{wpr}+\\{wtemp}*\\{wpi}+\\{wi};{}$\6
\4${}\}{}$\2\6
\&{if} ${}(\\{isign}\E\T{1}){}$\5
${}\{{}$\1\6
${}\\{data}[\T{1}]\K(\\{h1r}\K\\{data}[\T{1}])+\\{data}[\T{2}];{}$\6
${}\\{data}[\T{2}]\K\\{h1r}-\\{data}[\T{2}];{}$\6
\4${}\}{}$\2\6
\&{else}\5
${}\{{}$\1\6
${}\\{data}[\T{1}]\K\\{c1}*((\\{h1r}\K\\{data}[\T{1}])+\\{data}[\T{2}]);{}$\6
${}\\{data}[\T{2}]\K\\{c1}*(\\{h1r}-\\{data}[\T{2}]);{}$\6
${}\\{four1}(\\{data},\39\|n\GG\T{1},\39{-}\T{1});{}$\6
\4${}\}{}$\2\6
\4${}\}{}$\2\par
\U22.\fi

\M{35}The \PB{\\{convlv}(\&{double} \\{data}[\,]${},{}$\&{unsigned} \&{long} %
\|n${},{}$\&{double} \\{respns}[\,]${},{}$\&{unsigned} \&{long} \|m${},{}$%
\&{int} \\{isign}${},{}$\&{double} \\{ans}[\,])} routine convolves or
deconvolves
a real data set \PB{\\{data}[\T{1...}\|n]} (including any user-supplied zero
padding)
with a response function \PB{\\{respns}[\T{1...}\|n]}. The response function
must be
stored in wrap-around order in the first \PB{\|m} elements of respns, where %
\PB{\|m}
is an odd integer less than or equal to \PB{\|n}. Wrap-around order means
that the first half of the array respns contains the impulse response
function at positive times, while the second half of the array contains
the impulse response function at negative times, counting down from the
highest element \PB{\\{respns}[\|m]}. On input, \PB{\\{isign}} is $+1$ for
convolution, and
$-1$ for deconvolution. The answer is returned in the first \PB{\|n} components
of \PB{\\{ans}}. However, \PB{\\{ans}} {\sl must} be supplied in the calling
program with
dimensions \PB{$[\T{1...2}*\|n]$}, for consistency with the \PB{\\{twofft}}
routine.
Here \PB{\|n} {\sl must} be an integer power of two.
The \PB{\\{convlv}} routine is adopted from {\sl Numerical Recipes in C}, 2nd
Edn
(Cambridge University Press, New York, 1994).

\Y\B\4\X35:Routine for numerical convolution\X${}\E{}$\6
\&{char} \\{convlv}(\&{double} \\{data}[\,]${},\39{}$\&{unsigned} \&{long} %
\|n${},\39{}$\&{double} \\{respns}[\,]${},\39{}$\&{unsigned} \&{long} \|m${},%
\39{}$\&{int} \\{isign}${},\39{}$\&{double} \\{ans}[\,])\1\1\2\2\6
${}\{{}$\1\6
\&{void} \\{realft}(\&{double} \\{data}[\,]${},\39{}$\&{unsigned} \&{long} %
\|n${},\39{}$\&{int} \\{isign});\6
\&{void} \\{twofft}(\&{double} \\{data1}[\,]${},\39{}$\&{double} \\{data2}[%
\,]${},\39{}$\&{double} \\{fft1}[\,]${},\39{}$\&{double} \\{fft2}[\,]${},\39{}$%
\&{unsigned} \&{long} \|n);\6
\&{unsigned} \&{long} \|i${},{}$ \\{no2};\6
\&{double} \\{dum}${},{}$ \\{mag2}${},{}$ ${}{*}\\{fft};{}$\7
${}\\{fft}\K\\{dvector}(\T{1},\39\|n\LL\T{1});{}$\6
\&{for} ${}(\|i\K\T{1};{}$ ${}\|i\Z(\|m-\T{1})/\T{2};{}$ ${}\|i\PP){}$\1\5
${}\\{respns}[\|n+\T{1}-\|i]\K\\{respns}[\|m+\T{1}-\|i];{}$\2\6
\&{for} ${}(\|i\K(\|m+\T{3})/\T{2};{}$ ${}\|i\Z\|n-(\|m-\T{1})/\T{2};{}$ ${}\|i%
\PP){}$\1\5
${}\\{respns}[\|i]\K\T{0.0};{}$\2\6
${}\\{twofft}(\\{data},\39\\{respns},\39\\{fft},\39\\{ans},\39\|n);{}$\6
${}\\{no2}\K\|n\GG\T{1};{}$\6
\&{for} ${}(\|i\K\T{2};{}$ ${}\|i\Z\|n+\T{2};{}$ ${}\|i\MRL{+{\K}}\T{2}){}$\5
${}\{{}$\1\6
\&{if} ${}(\\{isign}\E\T{1}){}$\5
${}\{{}$\1\6
${}\\{ans}[\|i-\T{1}]\K(\\{fft}[\|i-\T{1}]*(\\{dum}\K\\{ans}[\|i-\T{1}])-%
\\{fft}[\|i]*\\{ans}[\|i])/\\{no2};{}$\6
${}\\{ans}[\|i]\K(\\{fft}[\|i]*\\{dum}+\\{fft}[\|i-\T{1}]*\\{ans}[\|i])/%
\\{no2};{}$\6
\4${}\}{}$\2\6
\&{else} \&{if} ${}(\\{isign}\E{-}\T{1}){}$\5
${}\{{}$\1\6
\&{if} ${}((\\{mag2}\K\\{ans}[\|i-\T{1}]*\\{ans}[\|i-\T{1}]+\\{ans}[\|i]*%
\\{ans}[\|i])\E\T{0.0}){}$\5
${}\{{}$\1\6
\\{log}(\.{"Attempt\ of\ deconvol}\)\.{ving\ at\ zero\ respons}\)\.{e\ in\
convlv()."});\6
\&{return} (\T{1});\6
\4${}\}{}$\2\6
${}\\{ans}[\|i-\T{1}]\K(\\{fft}[\|i-\T{1}]*(\\{dum}\K\\{ans}[\|i-\T{1}])+%
\\{fft}[\|i]*\\{ans}[\|i])/\\{mag2}/\\{no2};{}$\6
${}\\{ans}[\|i]\K(\\{fft}[\|i]*\\{dum}-\\{fft}[\|i-\T{1}]*\\{ans}[\|i])/%
\\{mag2}/\\{no2};{}$\6
\4${}\}{}$\2\6
\&{else}\5
${}\{{}$\1\6
\\{log}(\.{"No\ meaning\ for\ isig}\)\.{n\ in\ convlv()."});\6
\&{return} (\T{1});\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
${}\\{ans}[\T{2}]\K\\{ans}[\|n+\T{1}];{}$\6
${}\\{realft}(\\{ans},\39\|n,\39{-}\T{1});{}$\6
${}\\{free\_dvector}(\\{fft},\39\T{1},\39\|n\LL\T{1});{}$\6
\&{return} (\T{0});\6
\4${}\}{}$\2\par
\U22.\fi

\M{36}The \PB{\&{void} \\{sgcoeff}(\&{double} \|c[\,]${},{}$\&{int} %
\\{np}${},{}$\&{int} \\{nl}${},{}$\&{int} \\{nr}${},{}$\&{int} \\{ld}${},{}$%
\&{int} \|m)} routine
computes the coefficients \PB{\|c[\T{1...}\\{np}]} for Savitzky--Golay
filtering.
The coefficient vector \PB{\|c[\T{1...}\\{np}]} is returned in {\sl wrap-around
order}
consistent with the argument \PB{\\{respns}} in the {\sl Numerical Recipes in
C}
routine \PB{\\{convlv}}.
``Wrap-around order'' means that the first half of the array \PB{\\{respns}}
contains the impulse response function at positive times, while the second
half of the array contains the impulse response function at negative times,
counting down from the highest element \PB{\\{respns}[\|m]}.
The Savitzky--Golay filter coefficients are computed for \PB{\\{nl}}
leftward (past) data points and \PB{\\{nr}} rightward (future) data points,
making
the total number of data points used in the window as $\PB{\\{np}}=\PB{\\{nl}}+%
\PB{\\{nr}}+1$.
\PB{\\{ld}} is the order of the derivative desired (for example, $\PB{%
\\{ld}}=0$ for smoothed
function). Here $m$ is the order of the smoothing polynomial, also equal to the
highest conserved moment; usual values are $\PB{\|m}=2$ or $\PB{\|m}=4$.
The \PB{\\{sgcoeff}} routine is adopted from {\sl Numerical Recipes in C}, 2nd
Edn
(Cambridge University Press, New York, 1994).

\Y\B\4\X36:Routine for computation of coefficients for Savitzky--Golay
filtering\X${}\E{}$\6
\&{char} \\{sgcoeff}(\&{double} \|c[\,]${},\39{}$\&{int} \\{np}${},\39{}$%
\&{int} \\{nl}${},\39{}$\&{int} \\{nr}${},\39{}$\&{int} \\{ld}${},\39{}$\&{int}
\|m)\1\1\2\2\6
${}\{{}$\1\6
\&{void} \\{lubksb}(\&{double} ${}{*}{*}\|a,\39{}$\&{int} \|n${},\39{}$\&{int}
${}{*}\\{indx},\39{}$\&{double} \|b[\,]);\6
\&{void} \\{ludcmp}(\&{double} ${}{*}{*}\|a,\39{}$\&{int} \|n${},\39{}$\&{int}
${}{*}\\{indx},\39{}$\&{double} ${}{*}\|d);{}$\6
\&{int} \\{imj}${},{}$ \\{ipj}${},{}$ \|j${},{}$ \|k${},{}$ \\{kk}${},{}$ %
\\{mm}${},{}$ ${}{*}\\{indx};{}$\6
\&{double} \|d${},{}$ \\{fac}${},{}$ \\{sum}${},{}$ ${}{*}{*}\|a,{}$ ${}{*}%
\|b;{}$\7
\&{if} ${}(\\{np}<\\{nl}+\\{nr}+\T{1}\V\\{nl}<\T{0}\V\\{nr}<\T{0}\V\\{ld}>\|m\V%
\\{nl}+\\{nr}<\|m){}$\5
${}\{{}$\1\6
\\{log}(\.{"Inconsistent\ argume}\)\.{nts\ detected\ in\ rout}\)\.{ine\
sgcoeff."});\6
\&{return} (\T{1});\6
\4${}\}{}$\2\6
${}\\{indx}\K\\{ivector}(\T{1},\39\|m+\T{1});{}$\6
${}\|a\K\\{dmatrix}(\T{1},\39\|m+\T{1},\39\T{1},\39\|m+\T{1});{}$\6
${}\|b\K\\{dvector}(\T{1},\39\|m+\T{1});{}$\6
\&{for} ${}(\\{ipj}\K\T{0};{}$ ${}\\{ipj}\Z(\|m\LL\T{1});{}$ ${}\\{ipj}\PP){}$\5
${}\{{}$\1\6
${}\\{sum}\K(\\{ipj}\?\T{0.0}:\T{1.0});{}$\6
\&{for} ${}(\|k\K\T{1};{}$ ${}\|k\Z\\{nr};{}$ ${}\|k\PP){}$\1\5
${}\\{sum}\MRL{+{\K}}\\{pow}{}$((\&{double}) \|k${},\39{}$(\&{double}) %
\\{ipj});\2\6
\&{for} ${}(\|k\K\T{1};{}$ ${}\|k\Z\\{nl};{}$ ${}\|k\PP){}$\1\5
${}\\{sum}\MRL{+{\K}}\\{pow}{}$((\&{double}) ${}{-}\|k,\39{}$(\&{double}) %
\\{ipj});\2\6
${}\\{mm}\K(\\{ipj}<\T{2}*\|m-\\{ipj}\?\\{ipj}:\T{2}*\|m-\\{ipj});{}$\6
\&{for} ${}(\\{imj}\K{-}\\{mm};{}$ ${}\\{imj}\Z\\{mm};{}$ ${}\\{imj}\MRL{+{\K}}%
\T{2}){}$\1\5
${}\|a[\T{1}+(\\{ipj}+\\{imj})/\T{2}][\T{1}+(\\{ipj}-\\{imj})/\T{2}]\K%
\\{sum};{}$\2\6
\4${}\}{}$\2\6
${}\\{ludcmp}(\|a,\39\|m+\T{1},\39\\{indx},\39{\AND}\|d);{}$\6
\&{for} ${}(\|j\K\T{1};{}$ ${}\|j\Z\|m+\T{1};{}$ ${}\|j\PP){}$\1\5
${}\|b[\|j]\K\T{0.0};{}$\2\6
${}\|b[\\{ld}+\T{1}]\K\T{1.0};{}$\6
${}\\{lubksb}(\|a,\39\|m+\T{1},\39\\{indx},\39\|b);{}$\6
\&{for} ${}(\\{kk}\K\T{1};{}$ ${}\\{kk}\Z\\{np};{}$ ${}\\{kk}\PP){}$\1\5
${}\|c[\\{kk}]\K\T{0.0};{}$\2\6
\&{for} ${}(\|k\K{-}\\{nl};{}$ ${}\|k\Z\\{nr};{}$ ${}\|k\PP){}$\5
${}\{{}$\1\6
${}\\{sum}\K\|b[\T{1}];{}$\6
${}\\{fac}\K\T{1.0};{}$\6
\&{for} ${}(\\{mm}\K\T{1};{}$ ${}\\{mm}\Z\|m;{}$ ${}\\{mm}\PP){}$\1\5
${}\\{sum}\MRL{+{\K}}\|b[\\{mm}+\T{1}]*(\\{fac}\MRL{*{\K}}\|k);{}$\2\6
${}\\{kk}\K((\\{np}-\|k)\MOD\\{np})+\T{1};{}$\6
${}\|c[\\{kk}]\K\\{sum};{}$\6
\4${}\}{}$\2\6
${}\\{free\_dvector}(\|b,\39\T{1},\39\|m+\T{1});{}$\6
${}\\{free\_dmatrix}(\|a,\39\T{1},\39\|m+\T{1},\39\T{1},\39\|m+\T{1});{}$\6
${}\\{free\_ivector}(\\{indx},\39\T{1},\39\|m+\T{1});{}$\6
\&{return} (\T{0});\6
\4${}\}{}$\2\par
\U22.\fi

\M{37}The \PB{\\{sgfilter}(\&{double} \\{yr}[\,]${},{}$\&{double} \\{yf}[%
\,]${},{}$\&{int} \\{mm}${},{}$\&{int} \\{nl}${},{}$\&{int} \\{nr}${},{}$%
\&{int} \\{ld}${},{}$\&{int} \|m)}
routine provides the interface for the actual Savitzky--Golay filtering of
data. As input, this routine takes the following parameters:
\varitem[\PB{\\{yr}[\T{1...}\\{mm}]}]%
{A vector containing the raw, unfiltered data}
\varitem[\PB{\\{mm}}]%
{The number of data points in the input vector}
\varitem[\PB{\\{nl}}]%
{The number of samples $n_L$ to use to the ``left'' of the basis
sample in the regression window (kernel). The total number of samples in
the window will be $nL+nR+1$.}
\varitem[\PB{\\{nr}}]%
{The number of samples $n_R$ to use to the ``right'' of the basis
sample in the regression window (kernel). The total number of samples in
the window will be $nL+nR+1$.}
\varitem[\PB{\|m}]%
{The order $m$ of the polynomial
$p(x)=a_0+a_1(x-x_k)+a_2(x-x_k)^2+\ldots+a_m (x-x_k)^m$ to use in the
regression analysis leading to the Savitzky--Golay coefficients.
Typical values are between $m=2$ and $m=6$. Beware of too high values,
which easily makes the regression too sensitive, with an oscillatory
result.}
\varitem[\PB{\\{ld}}]%
{The order of the derivative to extract from the Savitzky--Golay
smoothing algorithm. For regular Savitzky--Golay smoothing of the input
data as such, use $l_D=0$. For the Savitzky--Golay smoothing and extraction
of derivatives, set $l_D$ to the order of the desired derivative and make
sure that you correctly interpret the scaling parameters as described in
{\sl Numerical Recipes in C}, 2nd Edn~(Cambridge University Press, New
York, 1994).}
\medskip
\noindent
On return, the Savitzky--Golay-filtered profile is contained in the vector
\PB{\\{yf}[\T{1...}\\{mm}]}.
Notice the somewhat peculiar accessing of the coefficients $c_j$ via the
\PB{$\|c[(\|j\G\T{0}\?\|j+\T{1}:\\{nr}+\\{nl}+\T{2}+\|j)]$} construction in
this routine. This reflects the
{\sl wrap-around storage} of the coefficients, where $c[1]=c_0$, $c[2]=c_1$,
$\ldots$, $c[\PB{\\{nr}}+1]=c_{n_R}$, $c[\PB{\\{nr}}+2]=c_{-n_L}$, $c[\PB{%
\\{nr}}+3]=c_{-n_L+1}$,
$\ldots$, $c[\PB{\\{nr}}+\PB{\\{nl}}+1]=c_{-1}$.

\Y\B\4\X37:Routine for Savitzky--Golay filtering\X${}\E{}$\6
\&{char} \\{sgfilter}(\&{double} \\{yr}[\,]${},\39{}$\&{double} \\{yf}[\,]${},%
\39{}$\&{int} \\{mm}${},\39{}$\&{int} \\{nl}${},\39{}$\&{int} \\{nr}${},\39{}$%
\&{int} \\{ld}${},\39{}$\&{int} \|m)\1\1\2\2\6
${}\{{}$\1\6
\&{int} \\{np}${}\K\\{nl}+\T{1}+\\{nr};{}$\6
\&{double} ${}{*}\|c;{}$\6
\&{char} \\{retval};\6
\8\#\&{if} \.{CONVOLVE\_WITH\_NR\_CONVLV}\C{ Please do not use this $\ldots$ }\7
${}\|c\K\\{dvector}(\T{1},\39\\{mm}){}$;\C{ Size required by the {\sl NR in C} %
\PB{\\{convlv}} routine }\6
${}\\{retval}\K\\{sgcoeff}(\|c,\39\\{np},\39\\{nl},\39\\{nr},\39\\{ld},\39%
\|m);{}$\6
\&{if} ${}(\\{retval}\E\T{0}){}$\1\5
${}\\{convlv}(\\{yr},\39\\{mm},\39\|c,\39\\{np},\39\T{1},\39\\{yf});{}$\2\6
${}\\{free\_dvector}(\|c,\39\T{1},\39\\{mm});{}$\6
\8\#\&{else}\C{ $\ldots$ use this instead. (Strongly recommended.) }\7
\&{int} \|j;\6
\&{long} \&{int} \|k;\7
${}\|c\K\\{dvector}(\T{1},\39\\{nl}+\\{nr}+\T{1}){}$;\C{ Size required by
direct convolution }\6
${}\\{retval}\K\\{sgcoeff}(\|c,\39\\{np},\39\\{nl},\39\\{nr},\39\\{ld},\39%
\|m);{}$\6
\&{if} ${}(\\{retval}\E\T{0}){}$\5
${}\{{}$\1\6
\&{for} ${}(\|k\K\T{1};{}$ ${}\|k\Z\\{nl};{}$ ${}\|k\PP){}$\5
${}\{{}$\C{ The first \PB{\\{nl}} samples }\1\6
\&{for} ${}(\\{yf}[\|k]\K\T{0.0},\39\|j\K{-}\\{nl};{}$ ${}\|j\Z\\{nr};{}$ ${}%
\|j\PP){}$\5
${}\{{}$\1\6
\&{if} ${}(\|k+\|j\G\T{1}){}$\5
${}\{{}$\1\6
${}\\{yf}[\|k]\MRL{+{\K}}\|c[(\|j\G\T{0}\?\|j+\T{1}:\\{nr}+\\{nl}+\T{2}+\|j)]*%
\\{yr}[\|k+\|j];{}$\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\&{for} ${}(\|k\K\\{nl}+\T{1};{}$ ${}\|k\Z\\{mm}-\\{nr};{}$ ${}\|k\PP){}$\5
${}\{{}$\C{ Samples $\PB{\\{nl}}+1 \ldots \PB{\\{mm}}-\PB{\\{nr}}$ }\1\6
\&{for} ${}(\\{yf}[\|k]\K\T{0.0},\39\|j\K{-}\\{nl};{}$ ${}\|j\Z\\{nr};{}$ ${}%
\|j\PP){}$\5
${}\{{}$\1\6
${}\\{yf}[\|k]\MRL{+{\K}}\|c[(\|j\G\T{0}\?\|j+\T{1}:\\{nr}+\\{nl}+\T{2}+\|j)]*%
\\{yr}[\|k+\|j];{}$\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\&{for} ${}(\|k\K\\{mm}-\\{nr}+\T{1};{}$ ${}\|k\Z\\{mm};{}$ ${}\|k\PP){}$\5
${}\{{}$\C{ The last \PB{\\{nr}} samples }\1\6
\&{for} ${}(\\{yf}[\|k]\K\T{0.0},\39\|j\K{-}\\{nl};{}$ ${}\|j\Z\\{nr};{}$ ${}%
\|j\PP){}$\5
${}\{{}$\1\6
\&{if} ${}(\|k+\|j\Z\\{mm}){}$\5
${}\{{}$\1\6
${}\\{yf}[\|k]\MRL{+{\K}}\|c[(\|j\G\T{0}\?\|j+\T{1}:\\{nr}+\\{nl}+\T{2}+\|j)]*%
\\{yr}[\|k+\|j];{}$\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
\4${}\}{}$\2\6
${}\\{free\_dvector}(\|c,\39\T{1},\39\\{nr}+\\{nl}+\T{1});{}$\6
\8\#\&{endif}\6
\&{return} (\\{retval});\C{ Returning \PB{\T{0}} if successful filtering }\6
\4${}\}{}$\2\par
\U22.\fi

\M{38}Routines for removing preceding path of filenames.
In this block all routines related to removing preceding path strings go.
Not really fancy programming, and no contribution to any increase of numerical
efficiency or precision; just for the sake of keeping a tidy terminal output
of the program. The \PB{\\{strip\_away\_path}(\,)} routine is typically called
when
initializing the program name string \PB{\\{progname}} from the command line
string
\PB{\\{argv}[\T{0}]}, and is typically located in the blocks related to parsing
of the
command line options.
The \PB{\\{strip\_away\_path}(\,)} routine takes a character string \PB{%
\\{filename}} as
argument, and returns a pointer to the same string but without any
preceding path segments.

\Y\B\4\X38:Routine for removing preceding path of filenames\X${}\E{}$\6
\X39:Routine for checking for a valid path character\X\7
\&{char} ${}{*}{}$\\{strip\_away\_path}(\&{char} \\{filename}[\,])\1\1\2\2\6
${}\{{}$\1\6
\&{int} \|j${},{}$ \|k${}\K\T{0};{}$\7
\&{while} (\\{pathcharacter}(\\{filename}[\|k]))\1\5
${}\|k\PP;{}$\2\6
${}\|j\K(\MM\|k){}$;\C{ this is the uppermost index of the full path+file
string }\6
\&{while} (\\{isalnum}((\&{int})(\\{filename}[\|j])))\1\5
${}\|j\MM;{}$\2\6
${}\|j\PP{}$;\C{ this is the lowermost index of the stripped file name }\6
\&{return} ${}({\AND}\\{filename}[\|j]);{}$\6
\4${}\}{}$\2\par
\U22.\fi

\M{39}In this program, valid path characters are any alphanumeric character or
`\.{.}', `\.{/}', `\.{\\}', `\.{\_}', `\.{-}', or `\.{+}'.

\Y\B\4\X39:Routine for checking for a valid path character\X${}\E{}$\6
\&{short} \\{pathcharacter}(\&{int} \\{ch})\1\1\2\2\6
${}\{{}$\1\6
\&{return} ${}(\\{isalnum}(\\{ch})\V(\\{ch}\E\.{'.'})\V(\\{ch}\E\.{'/'})\V(%
\\{ch}\E\.{'\\\\'})\V(\\{ch}\E\.{'\_'})\V(\\{ch}\E\.{'-'})\V(\\{ch}\E%
\.{'+'}));{}$\6
\4${}\}{}$\2\par
\U38.\fi

\M{40}The \PB{\&{void} \\{showsomehelp}(\&{void})} displays a brief help
message to standard
terminal output. This is where the caller always should end up in case
anything is wrong in the input parameters.

\Y\B\4\X40:Routine for displaying a brief help message on usage\X${}\E{}$\6
\X41:Routine for displaying a single line of the help message\X\7
\&{void} \\{showsomehelp}(\&{void})\1\1\2\2\6
${}\{{}$\1\6
${}\\{hl}(\.{"Usage:\ \%s\ [options]}\)\.{"},\39\\{progname});{}$\6
\\{hl}(\.{"Options:"});\6
\\{hl}(\.{"\ -h,\ --help"});\6
\\{hl}(\.{"\ \ \ \ Display\ this\ he}\)\.{lp\ message\ and\ exit\ }\)%
\.{clean."});\6
\\{hl}(\.{"\ -i,\ --inputfile\ <s}\)\.{tr>"});\6
\\{hl}(\.{"\ \ \ \ Specifies\ the\ f}\)\.{ile\ name\ from\ which\ }\)%
\.{unfiltered\ data\ is\ t}\)\.{o\ be\ read."});\6
\\{hl}(\.{"\ \ \ \ The\ input\ file\ }\)\.{should\ describe\ the\ }\)\.{input\
as\ two\ columns}\)\.{\ contain-"});\6
\\{hl}(\.{"\ \ \ \ ing\ \$x\$-\ and\ \$y}\)\.{\$-coordinates\ of\ the}\)\.{\
samples."});\6
\\{hl}(\.{"\ -o,\ --outputfile\ <}\)\.{str>"});\6
\\{hl}(\.{"\ \ \ \ Specifies\ the\ f}\)\.{ile\ name\ to\ which\ fi}\)\.{ltered\
data\ is\ to\ be}\)\.{\ written,"});\6
\\{hl}(\.{"\ \ \ \ again\ in\ a\ two-}\)\.{column\ format\ contai}\)\.{ning\ %
\$x\$-\ and\ \$y\$-co}\)\.{ordinates"});\6
\\{hl}(\.{"\ \ \ \ of\ the\ filtered}\)\.{\ samples.\ If\ this\ op}\)\.{tion\
is\ omitted,\ the}\)\.{\ generated"});\6
\\{hl}(\.{"\ \ \ \ filtered\ data\ w}\)\.{ill\ instead\ be\ writt}\)\.{en\ to\
the\ console\ (t}\)\.{erminal)."});\6
\\{hl}(\.{"\ -nl\ <nl>"});\6
\\{hl}(\.{"\ \ \ \ Specifies\ the\ n}\)\.{umber\ of\ samples\ nl\ }\)\.{to\ use%
\ to\ the\ 'left'}\)\.{\ of\ the"});\6
\\{hl}(\.{"\ \ \ \ basis\ sample\ in}\)\.{\ the\ regression\ wind}\)\.{ow\
(kernel).\ The\ tot}\)\.{al\ number"});\6
\\{hl}(\.{"\ \ \ \ of\ samples\ in\ t}\)\.{he\ window\ will\ be\ nL}\)%
\.{+nR+1."});\6
\\{hl}(\.{"\ -nr\ <nr>"});\6
\\{hl}(\.{"\ \ \ \ Specifies\ the\ n}\)\.{umber\ of\ samples\ nr\ }\)\.{to\ use%
\ to\ the\ 'right}\)\.{'\ of\ the"});\6
\\{hl}(\.{"\ \ \ \ basis\ sample\ in}\)\.{\ the\ regression\ wind}\)\.{ow\
(kernel).\ The\ tot}\)\.{al\ number"});\6
\\{hl}(\.{"\ \ \ \ of\ samples\ in\ t}\)\.{he\ window\ will\ be\ nL}\)%
\.{+nR+1."});\6
\\{hl}(\.{"\ -m\ <m>"});\6
\\{hl}(\.{"\ \ \ \ Specifies\ the\ o}\)\.{rder\ m\ of\ the\ polyno}\)\.{mial\
to\ use\ in\ the\ r}\)\.{egression"});\6
\\{hl}(\.{"\ \ \ \ analysis\ leadin}\)\.{g\ to\ the\ Savitzky-Go}\)\.{lay\
coefficients.\ Ty}\)\.{pical"});\6
\\{hl}(\.{"\ \ \ \ values\ are\ betw}\)\.{een\ m=2\ and\ m=6.\ Bew}\)\.{are\ of%
\ too\ high\ valu}\)\.{es,\ which"});\6
\\{hl}(\.{"\ \ \ \ easily\ makes\ th}\)\.{e\ regression\ too\ sen}\)\.{sitive,\
with\ an\ osci}\)\.{llatory"});\6
\\{hl}(\.{"\ \ \ \ result."});\6
\\{hl}(\.{"\ -ld\ <ld>"});\6
\\{hl}(\.{"\ \ \ \ Specifies\ the\ o}\)\.{rder\ of\ the\ derivati}\)\.{ve\ to\
extract\ from\ t}\)\.{he\ "});\6
\\{hl}(\.{"\ \ \ \ Savitzky--Golay}\)\.{\ smoothing\ algorithm}\)\.{.\ For\
regular\ Savitz}\)\.{ky-Golay"});\6
\\{hl}(\.{"\ \ \ \ smoothing\ of\ th}\)\.{e\ input\ data\ as\ such}\)\.{,\ use\
ld=0.\ For\ the\ }\)\.{Savitzky-"});\6
\\{hl}(\.{"\ \ \ \ Golay\ smoothing}\)\.{\ and\ extraction\ of\ d}\)%
\.{erivatives,\ set\ ld\ t}\)\.{o\ the"});\6
\\{hl}(\.{"\ \ \ \ order\ of\ the\ de}\)\.{sired\ derivative\ and}\)\.{\ make\
sure\ that\ you\ }\)\.{correctly"});\6
\\{hl}(\.{"\ \ \ \ interpret\ the\ s}\)\.{caling\ parameters\ as}\)\.{\
described\ in\ 'Numer}\)\.{ical"});\6
\\{hl}(\.{"\ \ \ \ Recipes\ in\ C',\ }\)\.{2nd\ Edn\ (Cambridge\ U}\)%
\.{niversity\ Press,\ New}\)\.{\ York,"});\6
\\{hl}(\.{"\ \ \ \ 1994)."});\6
\\{hl}(\.{"\ -v,\ --verbose"});\6
\\{hl}(\.{"\ \ \ \ Toggle\ verbose\ }\)\.{mode.\ (Default:\ Off.}\)\.{)\ \ This%
\ option\ shoul}\)\.{d\ always"});\6
\\{hl}(\.{"\ \ \ \ be\ omitted\ when}\)\.{ever\ no\ \ output\ file}\)\.{\ has\
been\ specified\ }\)\.{(that\ is"});\6
\\{hl}(\.{"\ \ \ \ to\ say,\ omit\ an}\)\.{y\ --verbose\ or\ -v\ op}\)\.{tion\
whenever\ --outp}\)\.{utfile\ or"});\6
\\{hl}(\.{"\ \ \ \ -o\ has\ been\ omi}\)\.{tted),\ as\ the\ verbos}\)\.{e\
logging\ otherwise\ }\)\.{will"});\6
\\{hl}(\.{"\ \ \ \ contaminate\ the}\)\.{\ filtered\ data\ strea}\)\.{m\
written\ to\ the\ con}\)\.{sole"});\6
\\{hl}(\.{"\ \ \ \ (terminal)."});\6
\4${}\}{}$\2\par
\U22.\fi

\M{41}In order to simplify the messaging, the \PB{\\{hl}(\&{const} \&{char}
${}{*}\\{format},\,\ldots\,)$} routine
acts as a simple front-end merely for compactifying the code by successive
calls to \PB{$\\{hl}(\,\ldots\,)$} rather than the full \PB{$\\{fprintf}(%
\\{stderr},\,\ldots\,)$}, still
maintaining all the functionality of string formatting in the regular
\PB{\\{printf}(\,)} or \PB{\\{fprintf}(\,)} syntax.

\Y\B\4\X41:Routine for displaying a single line of the help message\X${}\E{}$\6
\&{void} \\{hl}(\&{const} \&{char} ${}{*}\\{format},\39\,\ldots\,){}$\1\1 $\{$ %
\&{va\_list} \\{args}; \&{char} \6
\&{line} [\T{1024}]\1\5
;\2\6
${}\\{va\_start}(\\{args},\39\\{format}){}$;\C{ Initialize args by the \PB{%
\\{va\_start}(\,)} macro }\6
\\{vsprintf} ( \&{line} $,$ $\\{format},\39\\{args}$ )  ;\6
\\{va\_end}(\\{args});\C{ Terminate the use of args by the \PB{\\{va\_end}(\,)}
macro }\6
\\{sprintf} ( \&{line} ${}{+}\\{strlen}$ ( \&{line} ) $,$ \.{"\\n"} )  ;\C{
Always append newline }\6
\\{fprintf} $(\\{stdout},\39\.{"\%s"},\39$ \&{line} )  ;\6
\&{return}; $\}{}$\par
\U40.\fi

\M{42}Routine for obtaining the number of coordinate pairs in a file. This
routine is called prior to loading the input data, in order to automatically
extract the size needed for allocating the memory for the storage.

\Y\B\4\X42:Routine for obtaining the number of coordinate pairs in a file\X${}%
\E{}$\6
\&{long} \&{int} \\{num\_coordinate\_pairs}(\&{FILE} ${}{*}\\{file}){}$\1\1\2\2%
\6
${}\{{}$\1\6
\&{double} \\{tmp};\6
\&{int} \\{tmpch};\6
\&{long} \&{int} \\{mm}${}\K\T{0};{}$\7
${}\\{fseek}(\\{file},\39\T{0\$L},\39\.{SEEK\_SET}){}$;\C{ rewind file to
beginning }\6
\&{while} ${}((\\{tmpch}\K\\{getc}(\\{file}))\I\.{EOF}){}$\5
${}\{{}$\1\6
${}\\{ungetc}(\\{tmpch},\39\\{file});{}$\6
${}\\{fscanf}(\\{file},\39\.{"\%lf"},\39{\AND}\\{tmp}){}$;\C{ Read away the $x$
coordinate }\6
${}\\{fscanf}(\\{file},\39\.{"\%lf"},\39{\AND}\\{tmp}){}$;\C{ Read away the $y$
coordinate }\6
${}\\{mm}\PP;{}$\6
${}\\{tmpch}\K\\{getc}(\\{file}){}$;\C{ Read away any blanks or linefeeds }\6
\&{while} ${}((\\{tmpch}\I\.{EOF})\W(\R\\{isdigit}(\\{tmpch}))){}$\1\5
${}\\{tmpch}\K\\{getc}(\\{file});{}$\2\6
\&{if} ${}(\\{tmpch}\I\.{EOF}){}$\1\5
${}\\{ungetc}(\\{tmpch},\39\\{file});{}$\2\6
\4${}\}{}$\2\6
${}\\{fseek}(\\{file},\39\T{0\$L},\39\.{SEEK\_SET}){}$;\C{ rewind file to
beginning }\6
\&{return} (\\{mm});\6
\4${}\}{}$\2\par
\U22.\fi

\N{1}{43}Index.
\fi

\inx
\fin
\con
