Äîęóěĺíň âç˙ň čç ęýřŕ ďîčńęîâîé ěŕřčíű. Ŕäđĺń îđčăčíŕëüíîăî äîęóěĺíňŕ : http://vega.inp.nsk.su/~inest/OCAAS/cfitsio.ps
Äŕňŕ čçěĺíĺíč˙: Wed Mar 29 15:29:00 2000
Äŕňŕ číäĺęńčđîâŕíč˙: Mon Oct 1 19:54:11 2012
Ęîäčđîâęŕ:

Ďîčńęîâűĺ ńëîâŕ: arp 220
CFITSIO User's Guide
An Interface to FITS Format Files
for C Programmers
Version 2.0
HEASARC
Code 662
Goddard Space Flight Center
Greenbelt, MD 20771
USA
February 2000


Contents
1 Introduction 1
2 Creating the CFITSIO Library 3
2.1 Building the Library : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 3
2.1.1 Unix Systems : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 3
2.1.2 VMS : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 5
2.1.3 Windows PCs : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 5
2.1.4 OS/2 : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 5
2.1.5 Macintosh PCs : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 5
2.2 Testing the Library : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 6
2.3 Linking Programs with CFITSIO : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 7
2.4 Getting Started with CFITSIO : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 7
2.5 Example Program : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 8
2.6 Acknowledgements : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 9
3 A FITS Primer 11
4 Extended File Name Syntax 13
4.1 Overview : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 13
4.2 Detailed Filename Syntax : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 15
4.2.1 Filetype : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 16
4.2.2 Base Filename : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 19
4.2.3 Output File Name when Opening an Existing File : : : : : : : : : : : : : : : 20
4.2.4 Template File Name when Creating a New File : : : : : : : : : : : : : : : : : 21
4.2.5 HDU Location Specification : : : : : : : : : : : : : : : : : : : : : : : : : : : : 25
i

ii CONTENTS
4.2.6 Image Section : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 26
4.2.7 Column and Keyword Filtering Specification : : : : : : : : : : : : : : : : : : 27
4.2.8 Row Filtering Specification : : : : : : : : : : : : : : : : : : : : : : : : : : : : 28
4.2.9 Binning or Histogramming Specification : : : : : : : : : : : : : : : : : : : : : 35
5 CFITSIO Conventions and Guidelines 39
5.1 CFITSIO Definitions : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 39
5.2 CFITSIO Size Limitations : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 41
5.3 Multiple Access to the Same FITS File : : : : : : : : : : : : : : : : : : : : : : : : : : 42
5.4 Current Header Data Unit (CHDU) : : : : : : : : : : : : : : : : : : : : : : : : : : : 42
5.5 Function Names and Datatypes : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 42
5.6 Unsigned Integers : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 44
5.7 Character Strings : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 46
5.8 Implicit Data Type Conversion : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 47
5.9 Data Scaling : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 47
5.10 Error Status Values and the Error Message Stack : : : : : : : : : : : : : : : : : : : : 47
5.11 Variable­Length Arrays in Binary Tables : : : : : : : : : : : : : : : : : : : : : : : : : 48
5.12 Support for IEEE Special Values : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 50
5.13 When the Final Size of the FITS HDU is Unknown : : : : : : : : : : : : : : : : : : : 50
5.14 Local FITS Conventions supported by CFITSIO : : : : : : : : : : : : : : : : : : : : 51
5.14.1 Long String Keyword Values. : : : : : : : : : : : : : : : : : : : : : : : : : : : 51
5.14.2 Arrays of Fixed­Length Strings in Binary Tables : : : : : : : : : : : : : : : : 52
5.14.3 Keyword Units Strings : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 52
5.14.4 HIERARCH Convention for Extended Keyword Names : : : : : : : : : : : : 53
5.15 Optimizing Code for Maximum Processing Speed : : : : : : : : : : : : : : : : : : : : 54
5.15.1 Background Information: How CFITSIO Manages Data I/O : : : : : : : : : 54
5.15.2 Optimization Strategies : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 55
6 The CFITSIO Iterator Function 59
6.1 The Iterator Work Function : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 60
6.2 The Iterator Driver Function : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 62
6.3 Guidelines for Using the Iterator Function : : : : : : : : : : : : : : : : : : : : : : : : 63

CONTENTS iii
7 Basic CFITSIO Interface Routines 65
7.1 CFITSIO Error Status Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 65
7.2 FITS File Access Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 66
7.3 HDU Access Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 69
7.4 Header Keyword Read/Write Routines : : : : : : : : : : : : : : : : : : : : : : : : : : 71
7.5 Iterator Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 74
7.6 Primary Array or IMAGE Extension I/O Routines : : : : : : : : : : : : : : : : : : : 76
7.7 ASCII and Binary Table Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : : 77
7.7.1 Column Information Routines : : : : : : : : : : : : : : : : : : : : : : : : : : 78
7.7.2 Routines to Edit Rows or Columns : : : : : : : : : : : : : : : : : : : : : : : 80
7.7.3 Read and Write Column Data Routines : : : : : : : : : : : : : : : : : : : : : 81
7.8 Celestial Coordinate System Routines : : : : : : : : : : : : : : : : : : : : : : : : : : 83
7.8.1 Self­contained WCS Routines : : : : : : : : : : : : : : : : : : : : : : : : : : 84
7.8.2 WCS Routines that require the WCS library : : : : : : : : : : : : : : : : : : 85
7.9 Hierarchical Grouping Convention Support Routines : : : : : : : : : : : : : : : : : : 87
7.10 Row Selection and Calculator Routines : : : : : : : : : : : : : : : : : : : : : : : : : : 92
7.11 File Checksum Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 93
7.12 Date and Time Utility Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 95
7.13 General Utility Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 96
8 Specialized CFITSIO Interface Routines 103
8.1 Specialized FITS File Access Routines : : : : : : : : : : : : : : : : : : : : : : : : : : 103
8.2 Specialized HDU Access Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 104
8.3 Specialized Header Keyword Routines : : : : : : : : : : : : : : : : : : : : : : : : : : 106
8.3.1 Header Information Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : 106
8.3.2 Read and Write the Required Keywords : : : : : : : : : : : : : : : : : : : : : 106
8.3.3 Specialized Write Keyword Routines : : : : : : : : : : : : : : : : : : : : : : : 108
8.3.4 Insert Keyword Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 110
8.3.5 Specialized Read Keyword Routines : : : : : : : : : : : : : : : : : : : : : : : 111
8.3.6 Modify Keyword Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : : 113
8.3.7 Specialized Update Keyword Routines : : : : : : : : : : : : : : : : : : : : : 114
8.4 Define Data Scaling and Undefined Pixel Parameters : : : : : : : : : : : : : : : : : : 114

iv CONTENTS
8.5 Specialized FITS Primary Array or IMAGE Extension I/O Routines : : : : : : : : : 116
8.6 Specialized FITS ASCII and Binary Table Routines : : : : : : : : : : : : : : : : : : 119
8.6.1 Column Information Routines : : : : : : : : : : : : : : : : : : : : : : : : : : : 119
8.6.2 Low­Level Table Access Routines : : : : : : : : : : : : : : : : : : : : : : : : 120
8.6.3 Specialized Write Column Data Routines : : : : : : : : : : : : : : : : : : : : 121
8.6.4 Specialized Read Column Data Routines : : : : : : : : : : : : : : : : : : : : : 122
A Index of Routines 127
B Parameter Definitions 131
C CFITSIO Error Status Codes 137

Chapter 1
Introduction
CFITSIO is a machine­independent library of routines for reading and writing data files in the
FITS (Flexible Image Transport System) data format. It can also read IRAF format image files
by converting them on the fly into a temporary FITS format file. This library is written in ANSI
C and provides a powerful yet simple interface for accessing FITS files which will run on most
commonly used computers and workstations. CFITSIO supports all the features described in the
official NOST definition of the FITS format and can read and write all the currently defined types
of extensions, including ASCII tables (TABLE), Binary tables (BINTABLE) and IMAGE exten­
sions. The CFITSIO routines insulate the programmer from having to deal with the complicated
formatting details in the FITS file, however, it is assumed that users have a general knowledge
about the structure and usage of FITS files.
CFITSIO also contains a set of Fortran callable wrapper routines which allow Fortran programs
to call the CFITSIO routines. See the companion ``FITSIO User's Guide'' for the definition of the
Fortran subroutine calling sequences. These wrappers replace the older Fortran FITSIO library
which is no longer supported.
The CFITSIO package was initially developed by the HEASARC (High Energy Astrophysics Science
Archive Research Center) at the NASA Goddard Space Flight Center to convert various existing
and newly acquired astronomical data sets into FITS format and to further analyze data already in
FITS format. New features continue to be added to CFITSIO in large part due to contributions of
ideas or actual code from users of the package. The Integral Science Data Center in Switzerland,
and the XMM/ESTEC project in The Netherlands made especially significant contributions that
resulted in many of the new features that appeared in v2.0 of CFITSIO.
The latest version of the CFITSIO source code, documentation, and example programs are available
on the World­Wide Web or via anonymous ftp from:
http://heasarc.gsfc.nasa.gov/fitsio
ftp://legacy.gsfc.nasa.gov/software/fitsio/c
Any questions, bug reports, or suggested enhancements related to the CFITSIO package should be
sent to the primary author:
1

2 CHAPTER 1. INTRODUCTION
Dr. William Pence Telephone: (301) 286­4599
HEASARC, Code 662 E­mail: pence@tetra.gsfc.nasa.gov
NASA/Goddard Space Flight Center
Greenbelt, MD 20771, USA
This User's Guide assumes that readers already have a general understanding of the definition and
structure of FITS format files. Further information about FITS formats is available in the `FITS
User's Guide' and the `NOST FITS Standard', which are available from the NASA Science Office
of Standards and Technology at the address given below. Both of these documents are available
electronically from their Web site and via anonymous ftp at nssdc.gsfc.nasa.gov in the /pub/fits
directory. Any questions about FITS formats should be directed to the NOST, at:
NASA, Science Office of Standards and Technology
Code 633.2,
Goddard Space Flight Center
Greenbelt MD 20771, USA
WWW: http://www.gsfc.nasa.gov/astro/fits/fits—home.html
E­mail: fits@nssdca.gsfc.nasa.gov
(301) 286­2899
CFITSIO users may also be interested in the FTOOLS package of programs that can be used to
manipulate and analyze FITS format files. Information about FTOOLS can be obtained on the
Web or via anonymous ftp at:
http://heasarc.gsfc.nasa.gov/ftools
ftp://legacy.gsfc.nasa.gov/software/ftools/release

Chapter 2
Creating the CFITSIO Library
2.1 Building the Library
The CFITSIO code is contained in about 40 C source files (*.c) and header files (*.h). On
VAX/VMS systems 2 assembly­code files (vmsieeed.mar and vmsieeer.mar) are also needed.
CFITSIO has currently been tested on the following platforms:
OPERATING SYSTEM COMPILER
Sun OS gcc and cc (3.0.1)
Sun Solaris gcc and cc
Silicon Graphics IRIX gcc and cc
Dec Alpha OSF/1 gcc and cc
DECstation Ultrix gcc
Dec Alpha OpenVMS cc
DEC VAX/VMS gcc and cc
HP­UX gcc
IBM AIX gcc
Linux gcc
MkLinux DR3
Windows 95/98 Borland C++ V4.5
Windows NT Microsoft Visual C++ v5.0, v6.0
OS/2 gcc + EMX
MacOS 7.1 or greater Metrowerks 10.+
CFITSIO will probably run on most other Unix platforms. Cray supercomputers and IBM main­
frame computers are currently not supported.
2.1.1 Unix Systems
The CFITSIO library is built on Unix systems by typing:
3

4 CHAPTER 2. CREATING THE CFITSIO LIBRARY
? ./configure
? make
at the operating system prompt. Type ./configure and not simply `configure' to ensure that the
configure script in the current directory is run and not some other system­wide configure script. The
configure command customizes the Makefile for the particular system, then the `make' command
compiles the source files and builds the library.
On HP/UX systems, the environment variable CFLAGS should be set to ­Ae before running con­
figure to enable ''extended ANSI'' features.
By default, a set of Fortran­callable wrapper routines are also built and included in the CFITSIO
library. If these wrapper routines are not needed (i.e., the CFITSIO library will not be linked
to any Fortran applications which call FITSIO subroutines) then they may be omitted from the
build by typing 'make all­nofitsio' instead of simply typing 'make'. This will reduce the size of the
CFITSIO library slightly.
It may not be possible to staticly link programs that use CFITSIO on some platforms (namely,
on Solaris 2.6) due to the network drivers (which provide FTP and HTTP access to FITS files).
It is possible to make both a dynamic and a static version of the CFITSIO library, but network
file access will not be possible using the static version. To build the dynamic libcfitsio.so library
(on solaris), type 'make clean', then edit the Makefile to add ­fPIC or ­KPIC (gcc or cc) to the
CFLAGS line, then rebuild the library with 'make'. Once you're done, build the shared library
with
ld ­G ­z text ­o libcfitsio.so *.o
Then to get the staticly linkable libcfitsio.a library file do another make clean, undefine HAVE NET SERVICES
on the CFLAGS line and rebuild. It's unimportant whether or not you use ­fPIC for static builds.
When using the shared library the executable code is not copied into your program at link time and
instead the program locates the necessary library code at run time, normally through LD LIBRARY PATH
or some other method. The advantages are:
1. Less disk space if you build more than 1 program
2. Less memory if more than one copy of a program using the shared
library is running at the same time since the system is smart
enough to share copies of the shared library at run time.
3. Possibly easier maintenance since a new version of the shared
library can be installed without relinking all the software
that uses it (as long as the subroutine names and calling
sequences remain unchanged).
4. No run­time penalty.
The disadvantages are:

2.1. BUILDING THE LIBRARY 5
1. More hassle at runtime. You have to either build the programs
specially or have LD—LIBRARY—PATH set right.
2. There may be a slight start up penality, depending on where you are
reading the shared library and the program from and if your CPU is
either really slow or really heavily loaded.
2.1.2 VMS
On VAX/VMS and ALPHA/VMS systems the make.com command file may be used to build
the cfitsio.olb object library using the default G­floating point option for double variables. The
make dfloat.com and make ieee.com files may be used instead to build the library with the other
floating point options. Note that the getcwd function that is used in the group.c module may require
that programs using CFITSIO be linked with the ALPHA$LIBRARY:VAXCRTL.OLB library. See
the example link line in the next section of this document.
2.1.3 Windows PCs
A precompiled DLL version of CFITSIO is available for IBM­PC users in the file cfitsio dll.zip.
This zip archive also contains other files and instructions on how to use the CFITSIO DLL library.
The CFITSIO library may be built using a suitable compiler. The makepc.bat file gives an example
of how to build CFITSIO with the Borland C++ v4.5 compiler. This file will probably need to
be edited to include the appropriate command switches if a different C compiler or linker is used.
The files cfitsio.dsp, cfitsio.dsw, and cookbook.dsp contain the Microsoft Developer workspace files
for building CFITSIO and the cookbook example program on WindowsNT using Microsoft Visual
C++ 5.0 or 6.0.
2.1.4 OS/2
On OS/2 systems, CFITSIO can be built by typing 'make ­f makefile.os2'. This makefile requires
the GCC compiler and EMX library, which are available from many Internet sites containing OS/2
software, such as
ftp­os2.nmsu.edu/pub/os2/dev/emx/v0.9c and
ftp.leo.org/pub/comp/os/os2/leo/devtools/emx+gcc.
2.1.5 Macintosh PCs
The MacOS version of the CFITSIO library can be built by (1) un binhex and unstuff cfit­
sio mac.sit.hqx, (2) put CFitsioPPC.mcp in the cfitsio directory, and (3) load CFitsioPPC.mcp
into CodeWarrior Pro 2 and make. This builds the cfitsio library for PPC. There are also targets
for both the test program and the speed test program.

6 CHAPTER 2. CREATING THE CFITSIO LIBRARY
To use the MacOS port you can add Cfitsio PPC.lib to your CodeWarrior Pro 2 project. Note that
this only has been tested for the PPC and probably won't work on 68k Macs.
2.2 Testing the Library
The CFITSIO library should be tested by building and running the testprog.c program that is
included with the release. On Unix systems, type:
% make testprog
% testprog ? testprog.lis
% diff testprog.lis testprog.out
% cmp testprog.fit testprog.std
On VMS systems, (assuming cc is the name of the C compiler command), type:
$ cc testprog.c
$ link testprog, cfitsio/lib, alpha$library:vaxcrtl/lib
$ run testprog
The testprog program should produce a FITS file called `testprog.fit' that is identical to the `test­
prog.std' FITS file included with this release. The diagnostic messages (which were piped to the file
testprog.lis in the Unix example) should be identical to the listing contained in the file testprog.out.
The 'diff' and 'cmp' commands shown above should not report any differences in the files. (There
may be some minor formating differences, such as the presence or absence of leading zeros, or 3
digit exponents in numbers, which can be ignored).
The Fortran wrappers in CFITSIO may be tested with the testf77 program on Unix systems with:
% f77 ­o testf77 testf77.f ­L. ­lcfitsio ­lnsl ­lsocket
or
% f77 ­f ­o testf77 testf77.f ­L. ­lcfitsio (under SUN O/S)
or
% f77 ­o testf77 testf77.f ­Wl,­L. ­lcfitsio ­lm ­lnsl ­lsocket (HP/UX)
% testf77 ? testf77.lis
% diff testf77.lis testf77.out
% cmp testf77.fit testf77.std
On machines running SUN O/S, Fortran programs must be compiled with the '­f' option to force
double precision variables to be aligned on 8­byte boundarys to make the fortran­declared variables
compatible with C. A similar compiler option may be required on other platforms. Failing to use
this option may cause the program to crash on FITSIO routines that read or write double precision
variables.

2.3. LINKING PROGRAMS WITH CFITSIO 7
Also note that on some systems, the output listing of the testf77 program may differ slightly from
the testf77.std template, if leading zeros are not printed by default before the decimal point when
using F format.
A few other utility programs are included with CFITSIO:
speed ­ measures the maximum throughput (in MB per second)
for writing and reading FITS files with CFITSIO.
listhead ­ lists all the header keywords in any FITS file
fitscopy ­ copies any FITS file (especially useful in conjunction
with the CFITSIO's extended input filename syntax).
cookbook ­ a sample program that peforms common read and
write operations on a FITS file.
iter—a, iter—b, iter—c ­ tests of the CFITSIO iterator routine
The first 4 of these utility programs can be compiled and linked by typing
% make program—name
2.3 Linking Programs with CFITSIO
When linking applications software with the CFITSIO library, several system libraries usually need
to be specified on the link comma Unix systems, the most reliable way to determine what libraries
are required is to type 'make testprog' and see what libraries the configure script has added. The
typical libraries that need to be added are ­lm (the math library) and ­lnsl and ­lsocket (needed
only for FTP and HTTP file access). These latter 2 libraries are not needed on VMS and Windows
platforms, because FTP file access is not currently supported on those platforms.
Note that when upgrading to a newer version of CFITSIO it is usually necessay to recompile, as
well as relink, the programs that use CFITSIO, because the definitions in fitsio.h often change.
2.4 Getting Started with CFITSIO
In order to effectively use the CFITSIO library as quickly as possible, it is recommended that new
users follow these steps:
1. Read the following `FITS Primer' chapter for an overview of the structure of FITS files. This is
especially important for users who are unfamiliar with the FITS table and image extensions.
2. Review the various topics discussed in Chapters 4 and 5 to become familiar with the conventions
and advanced features of the CFITSIO interface.

8 CHAPTER 2. CREATING THE CFITSIO LIBRARY
3. Refer to the cookbook.c, listhead.c, and fitscopy.c programs that are included with this re­
lease for examples of routines that perform various common FITS file operations. Type 'make
program name' to compile and link these programs on Unix systems.
4. Write a simple program to read or write a FITS file using the Basic Interface routines described
in Chapter 7.
5. Scan through the more specialized routines that are described in Chapter 8 to become familiar
with the functionality that they provide.
2.5 Example Program
The following listing shows an example of how to use the CFITSIO routines in a C program. The
error checking of the returned status value has been omitted for the sake of clarity. Refer to the
cookbook.c program that is included with the CFITSIO distribution for other example programs.
This program creates a new FITS file, containing a FITS image. An `EXPOSURE' keyword is
written to the header, then the image data are writen to the FITS file before closing the FITS file.
#include ''fitsio.h'' /* required by every program that uses CFITSIO */
main()
--
fitsfile *fptr; /* pointer to the FITS file; defined in fitsio.h */
int status, ii, jj;
long fpixel = 1, naxis = 2, nelements, exposure;
long naxes[2] = -- 300, 200 ť; /* image is 300 pixels wide by 200 rows */
short array[200][300];
status = 0; /* initialize status before calling fitsio routines */
fits—create—file(&fptr, ''testfile.fits'', &status); /* create new file */
/* Create the primary array image (16­bit short integer pixels */
fits—create—img(fptr, SHORT—IMG, naxis, naxes, &status);
/* Write a keyword; must pass the ADDRESS of the value */
exposure = 1500.;
fits—update—key(fptr, TLONG, ''EXPOSURE'', &exposure,
''Total Exposure Time'', &status);
/* Initialize the values in the image with a linear ramp function */
for (jj = 0; jj ! naxes[1]; jj++)
for (ii = 0; ii ! naxes[0]; ii++)
array[jj][ii] = ii + jj;
nelements = naxes[0] * naxes[1]; /* number of pixels to write */

2.6. ACKNOWLEDGEMENTS 9
/* Write the array of integers to the image */
fits—write—img(fptr, TSHORT, fpixel, nelements, array[0], &status);
fits—close—file(fptr, &status); /* close the file */
fits—report—error(stderr, status); /* print out any error messages */
return( status );
ť
2.6 Acknowledgements
The development of many of the powerful features in CFITSIO was made possible through collab­
orations with many people or organizations from around the world. The following, in particular,
have made especially significant contributions:
Programmers from the Integral Science Data Center, Switzerland (namely, Jurek Borkowski, Bruce
O'Neel, and Don Jennings), designed the concept for the plug­in I/O drivers that was introduced
with CFITSIO 2.0. The use of `drivers' greatly simplified the low­level I/O, which in turn made
other new features in CFITSIO (e.g., support for compressed FITS files and support for IRAF
format image files) much easier to implement. Jurek Borkowski wrote the Shared Memory driver,
and Bruce O'Neel wrote the drivers for accessing FITS files over the network using the FTP, HTTP,
and ROOT protocols.
The ISDC also provided the template parsing routines (written by Jurek Borkowski) and the
hierarchical grouping routines (written by Don Jennings). The ISDC DAL (Data Access Layer)
routines are layered on top of CFITSIO and make extensive use of these features.
Uwe Lammers (XMM/ESA/ESTEC, The Netherlands) designed the high­performance lexical pars­
ing algorithm that is used to do on­the­fly filtering of FITS tables. This algorithm essentially
pre­compiles the user­supplied selection expression into a form that can be rapidly evaluated for
each row. Peter Wilson (RSTX, NASA/GSFC) then wrote the parsing routines used by CFITSIO
based on Lammers' design, combined with other techniques such as the CFITSIO iterator routine
to further enhance the data processing throughput. This effort also benefitted from a much earlier
lexical parsing routine that was developed by Kent Blackburn (NASA/GSFC).
The CFITSIO iterator function is loosely based on similar ideas developed for the XMM Data
Access Layer.
Peter Wilson (RSTX, NASA/GSFC) wrote the complete set of Fortran­callable wrappers for all the
CFITSIO routines, which in turn rely on the CFORTRAN macro developed by Burkhard Burow.
The syntax used by CFITSIO for filtering or binning input FITS files is based on ideas developed
for the AXAF Science Center Data Model by Jonathan McDowell, Antonella Fruscione, Aneta
Siemiginowska and Bill Joye. See http://heasarc.gsfc.nasa.gov/docs/journal/axaf7.html for further
description of the AXAF Data Model.
The file decompression code were taken directly from the gzip (GNU zip) program developed by
Jean­loup Gailly and others.

10 CHAPTER 2. CREATING THE CFITSIO LIBRARY
Doug Mink, SAO, provided the routines for converting IRAF format images into FITS format.
In addition, many other people have made valuable contributions to the development of CFITSIO.
These include (with apologies to others that may have inadvertently been omitted):
Steve Allen, Carl Akerlof, Keith Arnaud, Morten Krabbe Barfoed, Kent Blackburn, G Bodammer,
Romke Bontekoe, Lucio Chiappetti, Keith Costorf, Robin Corbet, John Davis, Richard Fink, Ning
Gan, Emily Greene, Gretchen Green, Joe Harrington, Cheng Ho, Phil Hodge, Jim Ingham, Yoshi­
taka Ishisaki, Diab Jerius, Mark Levine, Todd Karakaskian, Edward King, Scott Koch, Claire
Larkin, Rob Managan, Eric Mandel, John Mattox, Carsten Meyer, Emi Miyata, Stefan Mochnacki,
Mike Noble, Oliver Oberdorf, Clive Page, Arvind Parmar, Jeff Pedelty, Tim Pearson, Maren
Purves, Scott Randall, Chris Rogers, Arnold Rots, Barry Schlesinger, Robin Stebbins, Andrew
Szymkowiak, Allyn Tennant, Peter Teuben, James Theiler, Doug Tody, Shiro Ueno, Steve Wal­
ton, Archie Warnock, Alan Watson, Dan Whipple, Wim Wimmers, Peter Young, Jianjun Xu, and
Nelson Zarate.

Chapter 3
A FITS Primer
This section gives a brief overview of the structure of FITS files. Users should refer to the documen­
tation available from the NOST, as described in the introduction, for more detailed information on
FITS formats.
FITS was first developed in the late 1970's as a standard data interchange format between various
astronomical observatories. Since then FITS has become the standard data format supported by
most astronomical data analysis software packages.
A FITS file consists of one or more Header + Data Units (HDUs), where the first HDU is called
the `Primary HDU', or `Primary Array'. The primary array contains an N­dimensional array of
pixels, such as a 1­D spectrum, a 2­D image, or a 3­D data cube. Five different primary datatypes
are supported: Unsigned 8­bit bytes, 16 and 32­bit signed integers, and 32 and 64­bit floating point
reals. FITS also has a convention for storing 16 and 32­bit unsigned integers (see the later section
entitled `Unsigned Integers' for more details). The primary HDU may also consist of only a header
with a null array containing no data pixels.
Any number of additional HDUs may follow the primary array; these additional HDUs are called
FITS `extensions'. There are currently 3 types of extensions defined by the FITS standard:
ffl Image Extension ­ a N­dimensional array of pixels, like in a primary array
ffl ASCII Table Extension ­ rows and columns of data in ASCII character format
ffl Binary Table Extension ­ rows and columns of data in binary representation
In each case the HDU consists of an ASCII Header Unit followed by an optional Data Unit. For
historical reasons, each Header or Data unit must be an exact multiple of 2880 8­bit bytes long.
Any unused space is padded with fill characters (ASCII blanks or NULs depending on the type of
unit).
Each Header Unit consists of any number of 80­character keyword records or `card images' (reminis­
cent of the 80­column punched cards which were prevalent when the FITS standard was developed)
which have the general form:
11

12 CHAPTER 3. A FITS PRIMER
KEYNAME = value / comment string
NULLKEY = / comment: This keyword has no value
The keyword names may be up to 8 characters long and can only contain uppercase letters, the
digits 0­9, the hyphen, and the underscore character. The keyword name is (usually) followed by an
equals sign and a space character (= ) in columns 9 ­ 10 of the record, followed by the value of the
keyword which may be either an integer, a floating point number, a character string (enclosed in
single quotes), or a boolean value (the letter T or F). A keyword may also have a null or undefined
value if there is no specified value string, as in the second example.
The last keyword in the header is always the `END' keyword which has no value or comment
fields. There are many rules governing the exact format of a keyword record (see the NOST FITS
Standard) so it is better to rely on standard interface software like CFITSIO to correctly construct
or to parse the keyword records rather than try to deal directly with the raw FITS formats.
Each Header Unit begins with a series of required keywords which depend on the type of HDU.
These required keywords specify the size and format of the following Data Unit. The header may
contain other optional keywords to describe other aspects of the data, such as the units or scaling
values. Other COMMENT or HISTORY keywords are also frequently added to further document
the data file.
The optional Data Unit immediately follows the last 2880­byte block in the Header Unit. Some
HDUs do not have a Data Unit and only consist of the Header Unit.
If there is more than one HDU in the FITS file, then the Header Unit of the next HDU immediately
follows the last 2880­byte block of the previous Data Unit (or Header Unit if there is no Data Unit).
The main required keywords in FITS primary arrays or image extensions are:
ffl BITPIX -- defines the datatype of the array: 8, 16, 32, ­32, ­64 for unsigned 8--bit byte, 16--bit
integer, 32--bit integer, 32--bit IEEE floating point, and 64--bit IEEE double precision floating
point, respectively.
ffl NAXIS -- the number of dimensions in the array, usually 0, 1, 2, 3, or 4.
ffl NAXISn -- (n ranges from 1 to NAXIS) defines the size of each dimension.
FITS tables start with the keyword XTENSION = `TABLE' (for ASCII tables) or XTENSION =
`BINTABLE' (for binary tables) and have the following main keywords:
ffl TFIELDS -- number of fields or columns in the table
ffl NAXIS2 -- number of rows in the table
ffl TTYPEn -- for each column (n ranges from 1 to TFIELDS) gives the name of the column
ffl TFORMn -- the datatype of the column
ffl TUNITn -- the physical units of the column (optional)
Users should refer to the NOST documentation for more details about the required keywords and
their allowed values.

Chapter 4
Extended File Name Syntax
4.1 Overview
CFITSIO supports an extended syntax when specifying the name of the data file to be opened or
created that includes the following features:
ffl CFITSIO can read IRAF format images which have header file names that end with the
'.imh' extension, as well as reading and writing FITS files, This feature is implemented in
CFITSIO by first converting the IRAF image into a temporary FITS format file in memory,
then opening the FITS file. Any of the usual CFITSIO routines then may be used to read
the image header or data.
ffl FITS files on the internet can be read (and sometimes written) using the FTP, HTTP, or
ROOT protocols.
ffl FITS files can be piped between tasks on the stdin and stdout streams.
ffl FITS files can be read and written in shared memory. This can potentially achieve much better
data I/O performance compared to reading and writing the same FITS files on magnetic disk.
ffl Compressed FITS files in gzip or Unix COMPRESS format can be directly read.
ffl FITS table columns can be created, modified, or deleted 'on­the­fly' as the table is opened by
CFITSIO. This creates a virtual FITS file containing the modifications that is then opened
by the application program.
ffl Table rows may be selected, or filtered out, on the fly when the table is opened by CFITSIO,
based on an arbitrary user­specified expression. Only rows for which the expression evaluates
to 'TRUE' are retained in the copy of the table that is opened by the application program.
ffl Histogram images may be created on the fly by binning the values in table columns, resulting
in a virtual N­dimensional FITS image. The application program then only sees the FITS
image (in the primary array) instead of the original FITS table.
13

14 CHAPTER 4. EXTENDED FILE NAME SYNTAX
The latter 3 features in particular add very powerful data processing capabilities directly into
CFITSIO, and hence into every task that uses CFITSIO to read or write FITS files. For example,
these features transform a very simple program that just copies an input FITS file to a new output
file (like the `fitscopy' program that is distributed with CFITSIO) into a multipurpose FITS file
processing tool. By appending fairly simple qualifiers onto the name of the input FITS file, the user
can perform quite complex table editing operations (e.g., create new columns, or filter out rows
in a table) or create FITS images by binning or histogramming the values in table columns. In
addition, these functions have been coded using new state­of­the art algorithms that are, in some
cases, 10 ­ 100 times faster than previous widely used implementations.
Before describing the complete syntax for the extended FITS file names in the next section, here
are a few examples of FITS file names that give a quick overview of the allowed syntax:
ffl 'myfile.fits': the simplest case of a FITS file on disk in the current directory.
ffl 'myfile.imh': opens an IRAF format image file and converts it on the fly into a temporary
FITS format image in memory which can then be read with any other CFITSIO routine.
ffl 'myfile.fits.gz[events, 2]': opens and uncompresses the file myfile.fits then moves to
the extension which has the keywords EXTNAME = 'EVENTS' and EXTVER = 2.
ffl '­': a dash (minus sign) signifies that the input file is to be read from the stdin file stream,
or that the output file is to be written to the stdout stream.
ffl 'ftp://legacy.gsfc.nasa.gov/test/vela.fits': FITS files in any ftp archive site on the
internet may be directly opened with read­only access.
ffl 'http://legacy.gsfc.nasa.gov/software/test.fits': any valid URL to a FITS file on
the Web may be opened with read­only access.
ffl 'root://legacy.gsfc.nasa.gov/test/vela.fits': similar to ftp access except that it pro­
vides write as well as read access to the files across the network. This uses the root protocol
developed at CERN.
ffl 'shmem://h2[events]': opens the FITS file in a shared memory segment and moves to the
EVENTS extension.
ffl 'mem://': creates a scratch output file in core computer memory. The resulting 'file' will
disappear when the program exits, so this is mainly useful for testing purposes when one does
not want a permanent copy of the output file.
ffl 'myfile.fits[3; Images(10)]': opens a copy of the image contained in the 10th row of
the 'Images' column in the binary table in the 3th extension of the FITS file. The application
just sees this single image as the primary array.
ffl 'myfile.fits[1:512:2, 1:512:2]': opens a section of the input image ranging from the
1st to the 512th pixel in X and Y, and selects every second pixel in both dimensions, resulting
in a 256 x 256 pixel image in this case.

4.2. DETAILED FILENAME SYNTAX 15
ffl 'myfile.fits[EVENTS][col Rad = sqrt(X**2 + Y**2)]': creates and opens a temporary
file on the fly (in memory or on disk) that is identical to myfile.fits except that it will contain
a new column in the EVENTS extension called 'Rad' whose value is computed using the
indicated expresson which is a function of the values in the X and Y columns.
ffl 'myfile.fits[EVENTS][PHA ? 5]': creates and opens a temporary FITS files that is identi­
cal to 'myfile.fits' except that the EVENTS table will only contain the rows that have values
of the PHA column greater than 5. In general, any arbitrary boolean expression using a C or
Fortran­like syntax, which may combine AND and OR operators, may be used to select rows
from a table.
ffl 'myfile.fits[EVENTS][bin (X,Y)=1,2048,4]': creates a temporary FITS primary array
image which is computed on the fly by binning (i.e, computing the 2­dimensional histogram)
of the values in the X and Y columns of the EVENTS extension. In this case the X and Y
coordinates range from 1 to 2048 and the image pixel size is 4 units in both dimensions, so
the resulting image is 512 x 512 pixels in size.
ffl The final example combines many of these feature into one complex expression (it is broken
into several lines for clarity):
'ftp://legacy.gsfc.nasa.gov/data/sample.fits.gz[EVENTS]
[col phacorr = pha * 1.1 ­ 0.3][phacorr ?= 5.0 && phacorr != 14.0]
[bin (X,Y)=32]'
In this case, CFITSIO (1) copies and uncompresses the FITS file from the ftp site on the
legacy machine, (2) moves to the 'EVENTS' extension, (3) calculates a new column called
'phacorr', (4) selects the rows in the table that have phacorr in the range 5 to 14, and finally
(6) bins the remaining rows on the X and Y column coordinates, using a pixel size = 32 to
create a 2D image. All this processing is completely transparent to the application program,
which simply sees the final 2­D image in the primary array of the opened file.
4.2 Detailed Filename Syntax
This section describes the full syntax for the CFITSIO FITS file names, which can contain the
following components:
filetype://BaseFilename(outName)[HDUlocation][ImageSection]
for an image HDU, or
filetype://BaseFilename(outName)[HDUlocation][colFilter][rowFilter][binSpec]
for a table HDU, where each of these components is described below. The filetype, BaseFilename,
outName, HDUlocation, and ImageSection components, if present, must be given in that order,

16 CHAPTER 4. EXTENDED FILE NAME SYNTAX
but the colFilter, rowFilter, and binSpec specifiers may follow in any order. Regardless of the
order, however, the colFilter specifier, if present, will be processed first by CFITSIO, followed by
the rowFilter specifier, and finally by the binSpec specifier.
4.2.1 Filetype
The type of file determines the medium on which the file is located (e.g., disk or network) and,
hence, which internal device driver is used by CFITSIO to read and/or write the file. Currently
supported types are
file:// ­ file on local magnetic disk (default)
ftp:// ­ a readonly file accessed with the anonymous FTP protocol.
It also supports ftp://username:password@hostname/...
for accessing password­protected ftp sites.
http:// ­ a readonly file accessed with the HTTP protocol. It
does not support username:password like the ftp driver.
root:// ­ uses the CERN root protocol for writing as well as
reading files over the network.
shmem:// ­ opens or creates a file persists in the computer's
shared memory.
mem:// ­ opens a temporary file in core memory. The file
disappears when the program exits so this is mainly
useful for test purposes when a permanent output file
is not desired.
If the filetype is not specified, then type file:// is assumed. The double slashes '//' are optional
and may be omitted in most cases.
Notes about the root filetype
The original rootd server can be obtained from:
ftp://root.cern.ch/root/rootd.tar.gz
but, for it to work correctly with CFITSIO one has to use a modified version which supports a
command to return the length of the file. This modified version is available in rootd subdirectory
in the CFITSIO ftp area at
ftp://legacy.gsfc.nasa.gov/software/fitsio/c/root/rootd.tar.gz.
This small server is started either by inetd when a client requests a connection to a rootd server
or by hand (i.e. from the command line). The rootd server works with the ROOT TNetFile class.
It allows remote access to ROOT database files in either read or write mode. By default TNetFile

4.2. DETAILED FILENAME SYNTAX 17
assumes port 432 (which requires rootd to be started as root). To run rootd via inetd add the
following line to /etc/services:
rootd 432/tcp
and to /etc/inetd.conf, add the following line:
rootd stream tcp nowait root /user/rdm/root/bin/rootd rootd ­i
Force inetd to reread its conf file with ''kill ­HUP !pid inetd?''. You can also start rootd by hand
running directly under your private account (no root system priviliges needed). For example to
start rootd listening on port 5151 just type:
rootd ­p 5151
Notice: no & is needed. Rootd will go into background by itself.
Rootd arguments:
­i says we were started by inetd
­p port# specifies a different port to listen on
­d level level of debug info written to syslog
0 = no debug (default)
1 = minimum
2 = medium
3 = maximum
Rootd can also be configured for anonymous usage (like anonymous ftp). To setup rootd to accept
anonymous logins do the following (while being logged in as root):
­ Add the following line to /etc/passwd:
rootd:*:71:72:Anonymous rootd:/var/spool/rootd:/bin/false
where you may modify the uid, gid (71, 72) and the home directory
to suite your system.
­ Add the following line to /etc/group:
rootd:*:72:rootd
where the gid must match the gid in /etc/passwd.
­ Create the directories:

18 CHAPTER 4. EXTENDED FILE NAME SYNTAX
mkdir /var/spool/rootd
mkdir /var/spool/rootd/tmp
chmod 777 /var/spool/rootd/tmp
Where /var/spool/rootd must match the rootd home directory as
specified in the rootd /etc/passwd entry.
­ To make writeable directories for anonymous do, for example:
mkdir /var/spool/rootd/pub
chown rootd:rootd /var/spool/rootd/pub
That's all. Several additional remarks: you can login to an anonymous server either with the
names ''anonymous'' or ''rootd''. The password should be of type user@host.do.main. Only the @
is enforced for the time being. In anonymous mode the top of the file tree is set to the rootd home
directory, therefore only files below the home directory can be accessed. Anonymous mode only
works when the server is started via inetd.
Notes about the shmem filetype:
Shared memory files are currently supported on most Unix platforms, where the shared memory
segments are managed by the operating system kernel and `live' independently of processes. They
are not deleted (by default) when the process which created them terminates, although they will
disappear if the system is rebooted. Applications can create shared memory files in CFITSIO by
calling:
fit—create—file(&fitsfileptr, ''shmem://h2'', &status);
where the root `file' names are currently restricted to be 'h0', 'h1', 'h2', 'h3', etc., up to a maxi­
mumn number defined by the the value of SHARED MAXSEG (equal to 16 by default). This is
a preliminary implementation of the shared memory interface and a more robust interface, which
will have fewer restrictions on the number of files and on their names, is planned for the future.
When opening an already existing FITS file in shared memory one calls the usual CFITSIO routine:
fits—open—file(&fitsfileptr, ''shmem://h7'', mode, &status)
The file mode can be READWRITE or READONLY just as with disk files. More than one process
can operate on READONLY mode files at the same time. CFITSIO supports proper filelocking
(both in READONLY and READWRITE modes), so calls to fits open file may be locked out until
another other process closes the file.
When an application is finished accessing a FITS file in a shared memory segment, it may close it
(and the file will remain in the system) with fits close file, or delete it with fits delete file. Phys­
ical deletion is postponed until the last process calls ffclos/ffdelt. fits delete file tries to obtain a

4.2. DETAILED FILENAME SYNTAX 19
READWRITE lock on the file to be deleted, thus it can be blocked if the object was not opened
in READWRITE mode.
A shared memory management utility program called `smem', is included with the CFITSIO dis­
tribution. It can be built by typing `make smem'; then type `smem ­h' to get a list of valid options.
Executing smem without any options causes it to list all the shared memory segments currently
residing in the system and managed by the shared memory driver. To get a list of all the shared
memory objects, run the system utility program `ipcs [­a]'.
4.2.2 Base Filename
The base filename is the name of the file optionally including the director/subdirectory path, and
in the case of `ftp', `http', and `root' filetypes, the machine identifier. Examples:
myfile.fits
!data.fits
/data/myfile.fits
fits.gsfc.nasa.gov/ftp/sampledata/myfile.fits.gz
When creating a new output file on magnetic disk (of type file://) if the base filename begins with
an exclamation point (!) then any existing file with that same basename will be deleted prior to
creating the new FITS file. Otherwise if the file to be created already exists, then CFITSIO will
return an error and will not overwrite the existing file. Note that the exclamation point, ' !', is a
special UNIX character, so if it is used on the command line rather than entered at a task prompt,
it must be preceded by a backslash to force the UNIX shell to ignore it.
The input file may be compressed with the gzip or Unix compress algorithms, in which case CFIT­
SIO will uncompress the file on the fly into a temporary file (in memory or on disk). Compressed
files may only be opened with read­only permission. When specifying the name of a compressed
FITS file it is not necessary to append the file suffix (e.g., '.gz' or '.Z'). If CFITSIO cannot find
the input file name without the suffix, then it will automatically search for a compressed file with
the same root name. In the case of reading ftp and http type files, CFITSIO generally looks for
a compressed version of the file first, before trying to open the uncompressed file. By default,
CFITSIO copies (and uncompressed if necessary) the ftp or http FITS file into memory on the
local machine before opening it. This will fail if the local machine does not have enough memory
to hold the whole FITS file, so in this case, the output filename specifier (see the next section) can
be used to further control how CFITSIO reads ftp and http files.
One special case is where the filename = '­' (a dash or minus sign), which signifies that the input
file is to be read from the stdin stream, or written to the stdout stream if a new output file is
being created. In the case of reading from stdin, CFITSIO first copies the whole stream into a
temporary FITS file (in memory or on disk), and subsequent reading of the FITS file occurs in this
copy. When writing to stdout, CFITSIO first constructs the whole file in memory (since random
access is required), then flushes it out to the stdout stream when the file is closed. This feature
allows FITS files to be piped between tasks in memory rather than having to create temporary

20 CHAPTER 4. EXTENDED FILE NAME SYNTAX
intermediate FITS files on disk. For example if task1 creates an output FITS file, and task2 reads
an input FITS file, the FITS file may be piped between the 2 tasks by specifying
task1 ­ --- task2 ­
where the vertical bar is the Unix piping symbol. This assumes that the 2 tasks read the name of
the FITS file off of the command line.
When specifying the name of the new FITS file to be created by fits create file, if the name is
preceded with an exclamation mark (!), then any existing file with the same name will be clobbered,
or overwritten, by the newly created file. Otherwise, CFITSIO will return an error if the file to be
created already exists.
4.2.3 Output File Name when Opening an Existing File
An optional output filename may be specified in parentheses immediately following base file name
to be opened. In a number of instances CFITSIO will create a temporary copy in memory of the
input FITS file before it is opened and passed to the application program. This happens by default
when opening a network FTP or HTTP­type file, when reading a compressed FITS file on a local
disk, when reading from the stdin stream, or when a column filter, row filter, or binning specifier is
included as part of the input file specification. If there is not enough memory to create the file copy,
then CFITSIO will exit with an error. In these cases one can force a permanent file to be created
on disk, instead of a temporary file in memory, by supplying the name in parentheses immediately
following the base file name. The output filename can include the ' !' clobber flag.
Thus, if the input filename to CFITSIO is:
file1.fits.gz(file2.fits)
then CFITSIO will uncompress `file1.fits.gz' into the local disk file `file2.fits' before opening it.
CFITSIO does not automatically delete the output file, so it will still exist after the application
program exits.
In some cases, several different temporary FITS files will be created in sequence, for instance, if
one opens a remote file using FTP, then filters rows in a binary table extension, then create an
image by binning a pair of columns. In this case, the remote file will be copied to a temporary
local file, then a second temporary file will be created containing the filtered rows of the table,
and finally a third temporary file containing the binned image will be created. In cases like this
where multiple files are created, the outfile specifier will be interpreted the name of the final file as
described below, in descending priority:
ffl as the name of the final image file if an image within a single binary table cell is opened or if
an image is created by binning a table column.
ffl as the name of the file containing the filtered table if a column filter and/or a row filter are
specified.

4.2. DETAILED FILENAME SYNTAX 21
ffl as the name of the local copy of the remote FTP or HTTP file.
ffl as the name of the uncompressed version of the FITS file, if a compressed FITS file on local
disk has been opened.
ffl otherwise, the output filename is ignored.
The output file specifier is useful when reading FTP or HTTP­type FITS files since it can be used
to create a local disk copy of the file that can be reused in the future. If the output file name =
`*' then a local file with the same name as the network file will be created. Note that CFITSIO
will behave differently depending on whether the remote file is compressed or not as shown by the
following examples:
ffl `ftp://remote.machine/tmp/myfile.fits.gz(*)' ­ the remote compressed file is copied to the
local compressed file `myfile.fits.gz', which is then uncompressed in local memory before being
opened and passed to the application program.
ffl `ftp://remote.machine/tmp/myfile.fits.gz(myfile.fits)' ­ the remote compressed file is copied
and uncompressed into the local file `myfile.fits'. This example requires less local memory
than the previous example since the file is uncompressed on disk instead of in memory.
ffl `ftp://remote.machine/tmp/myfile.fits(myfile.fits.gz)' ­ this will usually produce an error since
CFITSIO itself cannot compress files.
The exact behavior of CFITSIO in the latter case depends on the type of ftp server running on
the remote machine and how it is configured. In some cases, if the file `myfile.fits.gz' exists on the
remote machine, then the server will copy it to the local machine. In other cases the ftp server
will automatically create and transmit a compressed version of the file if only the uncompressed
version exists. This can get rather confusing, so users should use a certain amount of caution when
using the output file specifier with FTP or HTTP file types, to make sure they get the behavior
that they expect.
4.2.4 Template File Name when Creating a New File
When a new FITS file is created with a call to fits create file, the name of a template file may
be supplied in parentheses immediately following the name of the new file to be created. This
template is used to define the structure of one or more HDUs in the new file. The template file may
be another FITS file, in which case the newly created file will have exactly the same keywords in
each HDU as in the template FITS file, but all the data units will be filled with zeros. The template
file may also be an ASCII text file, where each line (in general) describes one FITS keyword record.
The format of the ASCII template file is described below.
Detailed Template Line Format
Each line of the template generally translates into one FITS keyword record. In addition, there are
several template directives, each preceded by a backslash character, which are used to indicate the

22 CHAPTER 4. EXTENDED FILE NAME SYNTAX
start and end of HDU definitions. Also, any template line that begins with the pound '#' character
is ignored by the template parser and may be use to insert comments into the template file itself.
The format of each template line follows very closely the format of the FITS keyword record:
KEYWORD = KEYVALUE / COMMENT
All the fields are optional, and only one field of each type per record is allowed. The fields must
appear in order. The result of parsing is one (or possibly more, in the case of a long keyvalue
field) 80 character FITS header record(s). For the purpose of parsing, space and TAB characters
(blanks) are equivalent and treated as separators.
The start of each record field is order dependent but position independent, except if the first 8
characters of a record are blanks then the entire line is treated as a FITS comment keyword (with
a blank keyword name) and copied verbatim into the FITS header. Thus lines can be indented,
but indentation is limited to a maximum of 7 spaces.
The KEYWORD field is limited to 8 characters in length and only the letters A­Z, digits 0­9,
and the hyphen and underscore character may be used, without any embedded spaces. Lowercase
letters in the template keyword name are converted to uppercase. The only exception to this is
when auto­indexing is used (see below).
The KEYWORD and KEYVALUE may optionally be separated by the ''='' character with optional
spaces allowed on either side of the ''=''.
KEYVALUE fields are parsed for data type using standard FITS rules. Allowed data types are:
­ logical : T or F character
­ integer : ­12345
­ real : ­1.234E+68
­ complex integer : (integer,integer)
­ complex real : (real,real)
­ string : any other format
The value may be forced to be interpreted as a character string by enclosing it in single quotes. An
undefined (null) value is specified if the template record only contains blanks following the ''='' or
between the ''='' and the ''/'' comment field delimiter.
Keyword values longer than 68 characters (for string data type) are permitted using the cfitsio long
string convention. They can either be specified as a single ''long'' line, or by using multiple lines
where the continuing lines contain the 'CONTINUE' keyword. Example:
LONGKEY = 'This is a long string value that is contin&'
CONTINUE 'ued over 2 records' / comment field here
The format of template lines with CONTINUE keyword is very strict: 3 spaces must follow CON­
TINUE and the rest of the line is copied verbatim to the FITS file.

4.2. DETAILED FILENAME SYNTAX 23
Note: contrary to the FITS standard, the template cannot have any blanks between real and
imaginary parts of a complex number (complex integer and complex real data types).
The start of a COMMENT field must be preceeded by ''/'', which is used to separate it from the
keyword value field. Exceptions are if the KEYWORD field contains COMMENT, HISTORY,
CONTINUE, or if the first 8 chars of the record are blanks.
Template Parser Directives
The template parser recognizes 3 special keywords (directives):
ffl ``include ­ must be followed by a filename. Forces parser to temporarily stop reading current
file and begin reading the include file. Once the parser reaches the end of the include file
it continues with the current one. Include files can be nested. HDU definitions can span
multiple files.
ffl ``group ­ marks beginning of GROUP definition
ffl ``end ­ marks end of GROUP definition
Formal Template Syntax
TEMPLATE = BLOCK [ BLOCK ... ]
BLOCK = -- HDU --- GROUP ť
GROUP = ``GROUP [ BLOCK ... ] ``END
HDU = XTENSION [ LINE ... ] -- XTENSION --- ``GROUP --- ``END --- EOF ť
LINE = [ KEYWORD [ = ] ] [ VALUE ] [ / COMMENT ]
X ... ­ X can be present 1 or more times
-- X --- Y ť ­ X or Y
[ X ] ­ X is optional
At the topmost level, the template defines 1 or more template blocks. Blocks can be either HDU
(Header Data Unit) or a GROUP. For each block the parser creates 1 (or more for GROUPs) FITS
file HDUs.
The start of an HDU definition is denoted with a template line containing either of the following
keywords:
'SIMPLE' : begins a Primary array (PHDU) definition. One per template is allowed and only as
a first keyword in the template file. If not present then an empty PHDU is created (of size 2880
bytes) and the first HDU defined in template files is saved as a 2nd HDU (first after dummy one).

24 CHAPTER 4. EXTENDED FILE NAME SYNTAX
'XTENSION' : begins any xtension HDU definition.
The end of an HDU definition is given by the next occurance of an 'XTENSION' keyword, a group
or end directive, or the end of the template file.
The start of a GROUP definition is denoted with the group directive, and the end of a GROUP
definition is denoted with the end directive. GROUP contains 0 or more member blocks (HDUs or
GROUPs). Member blocks of type GROUP can contain their own member blocks. The GROUP
definition itself occupies one FITS file HDU of special type (GROUP HDU), so if a template
specifies 1 group with 1 member HDU like:
``group
grpdescr = 'demo'
xtension bintable
# this bintable has 0 cols, 0 rows
``end
then the parser creates a FITS file with 3 HDUs :
1) dummy PHDU
2) GROUP HDU (has 1 member, which is bintable in HDU number 3)
3) bintable (member of GROUP in HDU number 2)
Technically speaking, the GROUP HDU is a BINTABLE with 6 columns. Applications can define
additional columns in a GROUP HDU using TFORMn and TTYPEn (where n is 7, 8, ....) keywords
or their auto­indexing equivalents.
For a more complicated example of a template file using the group directives, look at the sample.tpl
file that is included in the CFITSIO distribution.
Auto­indexing of Keywords
If a template keyword name ends with a ''#'' character, it is auto­indexed. The parser replaces
the '#' with the current integer keyword index value in the FITS header. The first keyword field
encountered in a given HDU definition ending with '#' is used as the index value incrementor.
Each time this keyword field (also ending with '#') is encountered in the header definition the
index value is incremented by 1.
All keyword fields ending with '#' encountered between index value incrementor keyword fields are
assigned the current index value. The resulting FITS keyword (i.e., after the '#' is replaced with
the index value) must be 8 characters or less in length. The following example demonstrates the
auto­indexing feature:
Template Record Resulting keyword (in GROUP HDU add 6)
DUMMY DUMMY
PARAM# PARAM1

4.2. DETAILED FILENAME SYNTAX 25
DUMMY# DUMMY1
PARAM PARAM
PARAM# PARAM2
TEST# TEST2
PARAM# PARAM3
TEST# TEST3
The index value and index value incrementor keyword field are reset to 1 for each HDU or to 7 for
each GROUP defined in the template.
Errors
In general fits execute template() function tries to be as atomic as possible, so either everything is
done or nothing is done. If an error occurs during parsing of the template, fits execute template()
will (try to) delete the top level BLOCK (with all its children if any) in which the error occured,
then it will stop reading the template file and it will return with an error.
4.2.5 HDU Location Specification
The optional HDU location specifier defines which HDU (Header­Data Unit, also known as an
`extension') within the FITS file to initially open. It must immediately follow the base file name
(or the output file name if present). If it is not specified then the first HDU (the primary array)
is opened. The HDU location specifier is required if the colFilter, rowFilter, or binSpec specifiers
are present, because the primary array is not a valid HDU for these operations. The HDU may be
specified either by absolute position number, starting with 0 for the primary array, or by reference
to the HDU name, and optionally, the version number and the HDU type of the desired extension.
The location of an image within a single cell of a binary table may also be specified, as described
below.
The absolute position of the extension is specified either by enclosed the number in square brackets
(e.g., `[1]' = the first extension following the primary array) or by preceded the number with a plus
sign (`+1'). To specify the HDU by name, give the name of the desired HDU (the value of the
EXTNAME or HDUNAME keyword) and optionally the extension version number (value of the
EXTVER keyword) and the extension type (value of the XTENSION keyword: IMAGE, ASCII or
TABLE, or BINTABLE), separated by commas and all enclosed in square brackets. If the value
of EXTVER and XTENSION are not specified, then the first extension with the correct value of
EXTNAME is opened. The extension name and type are not case sensitive, and the extension
type may be abbreviated to a single letter (e.g., I = IMAGE extension or primary array, A or T =
ASCII table extension, and B = binary table BINTABLE extension). If the HDU location specifier
is equal to `[PRIMARY]' or `[P]', then the primary array (the first HDU) will be opened.
FITS images are most commonly stored in the primary array or an image extension, but images
can also be stored as a vector in a single cell of a binary table (i.e. each row of the vector column
contains a different image). Such an image can be opened with CFITSIO by specifying the desired
column name and the row number after the binary table HDU specifier as shown in the following

26 CHAPTER 4. EXTENDED FILE NAME SYNTAX
examples. The column name is separated from the HDU specifier by a semicolon and the row
number is enclosed in parentheses. In this case CFITSIO copies the image from the table cell into
a temporary primary array before it is opened. The application program then just sees the image
in the primary array, without any extensions. The particular row to be opened may be specified
either by giving an absolute integer row number (starting with 1 for the first row), or by specifying
a boolean expression that evaluates to TRUE for the desired row. The first row that satisfies the
expression will be used. The row selection expression has the same syntax as described in the Row
Filter Specifier section, below.
Examples:
myfile.fits[3] ­ open the 3rd HDU following the primary array
myfile.fits+3 ­ same as above, but using the FTOOLS­style notation
myfile.fits[EVENTS] ­ open the extension that has EXTNAME = 'EVENTS'
myfile.fits[EVENTS, 2] ­ same as above, but also requires EXTVER = 2
myfile.fits[events,2,b] ­ same, but also requires XTENSION = 'BINTABLE'
myfile.fits[3; images(17)] ­ opens the image in row 17 of the 'images'
column in the 3rd extension of the file.
myfile.fits[3; images(exposure ? 100)] ­ as above, but opens the image
in the first row that has an 'exposure' column value
greater than 100.
4.2.6 Image Section
A subsection of an image can be opened by specifying the range of pixels (start:end), or with an
optional pixel increment (start:end:step), for each axis of the input image. A pixel step = 1 will
be assumed if it is not specified, and an asterisk, '*', may be used to specify the entire range of an
axis. The input image can be in the primary array, in an image extension, or in a vector cell of a
binary table. In the later 2 cases the extension name or number must be specified before the image
section specifier.
Examples:
myfile.fits[1:512:2, 2:512:2] ­ open a 256x256 pixel image
consisting of the odd numbered columns (1st axis) and
the even numbered rows (2nd axis) of the image in the
primary array of the file.
myfile.fits[*, 256:512] ­ open an image consisting of all the columns
in the input image, but only rows 256 through 512.
myfile.fits[*:2, 256:512:2] ­ same as above but keeping only
every other row and column in the input image.
myfile.fits[3][1:256,1:256] ­ opens a subsection of the image in

4.2. DETAILED FILENAME SYNTAX 27
the 3rd extension of the file.
myfile.fits[4; images(12)][*,*] ­ open the whole image contained
in the 12th row of the 'images' vector column
in the table in the 4th extension of the file.
When CFITSIO opens an image section it first creates a temporary file containing the image section
plus a copy of any other HDUs in the file. This temporary file is then opened by the application
program, so it is not possible to write to or modify the input file when specifying an image section.
Note that CFITSIO automatically updates the world coordinate system keywords in the header
of the image section, if they exist, so that the coordinate associated with each pixel in the image
section will be computed correctly.
4.2.7 Column and Keyword Filtering Specification
The optional column/keyword filtering specifier is used to modify the column structure and/or the
header keywords in the HDU that was selected with the previous HDU location specifier. This
filtering specifier must be enclosed in square brackets and can be distinguished from a general
row filter specifier (described below) by the fact that it begins with the string 'col ' and is not
immediately followed by an equals sign. The original file is not changed by this filtering operation,
and instead the modifications are made on a copy of the input FITS file (usually in memory),
which also contains a copy of all the other HDUs in the file. This temporary file is passed to the
application program and will persist only until the file is closed or until the program exits, unless
the outfile specifier (see above) is also supplied.
The column/keyword filter can be used to perform the following operations. More than one oper­
ation may be specified by separating them with semi­colons.
ffl Delete a column or keyword by listing the name preceeded by an exclamation mark (!), e.g.,
' !TIME' will delete the TIME column if it exists, otherwise the TIME keyword. An error is
returned if neither a column nor keyword with this name exists. Note that the exclamation
point, ' !', is a special UNIX character, so if it is used on the command line rather than entered
at a task prompt, it must be preceded by a backslash to force the UNIX shell to ignore it.
ffl Rename an existing column or keyword with the syntax 'NewName == OldName'. An error
is returned if neither a column nor keyword with this name exists.
ffl Append a new column or keyword to the table. To create a column, give the new name,
optionally followed by the datatype in parentheses, followed by a single equals sign and an
expression to be used to compute the value (e.g., 'newcol(1J) = 0' will create a new 32­bit
integer column called 'newcol' filled with zeros). The datatype is specified using the same
syntax that is allowed for the value of the FITS TFORMn keyword (e.g., 'I', 'J', 'E', 'D', etc.
for binary tables, and 'I8', F12.3', 'E20.12', etc. for ASCII tables). If the datatype is not
specified then an appropriate datatype will be chosen depending on the form of the expression
(may be a character string, logical, bit, long integer, or double column). An appropriate vector
count (in the case of binary tables) will also be added if not explicitly specified.

28 CHAPTER 4. EXTENDED FILE NAME SYNTAX
When creating a new keyword, the keyword name must be preceeded by a pound sign '#', and
the expression must evaluate to a scalar (i.e., cannot have a column name in the expression).
The comment string for the keyword may be specified in parentheses immediately following
the keyword name (instead of supplying a datatype as in the case of creating a new column).
ffl Recompute (overwrite) the values in an existing column or keyword by giving the name
followed by an equals sign and an arithmetic expression.
The expression that is used when appending or recomuting columns or keywords can be arbitrarily
complex and may be a function of other header keyword values and other columns (in the same
row). The full syntax and available functions for the expression are described below in the row
filter specification section.
For complex or commonly used operations, one can also place the operations into a text file and
import it into the column filter using the syntax '[col @filename.txt]'. The operations can extend
over multiple lines of the file, but multiple operations must still be separated by semicolons.
Examples:
[col !TIME; Good == STATUS] ­ deletes the TIME column and
renames the status column to 'Good'
[col PI=PHA * 1.1 + 0.2] ­ creates new PI column from PHA values
[col rate = rate/exposure] ­ recomputes the rate column by dividing
it by the EXPOSURE keyword value.
4.2.8 Row Filtering Specification
The optional row filter is a boolean expression enclosed in square brackets for filtering or selecting
rows from the input FITS table. A new FITS file is then created which contains only those rows
for which the boolean expression evaluates to true. (The primary array and any other extensions
in the input file are also copied to the new file). The original FITS file is closed and the new file is
opened and passed to the application program. The new file will persist only until the file is closed
or until the program exits, unless the output file specifier (see above) is also supplied.
The expression can be an arbitrarily complex series of operations performed on constants, keyword
values, and column data taken from the specified FITS TABLE extension.
Keyword and column data are referenced by name. Any string of characters not surrounded by
quotes (ie, a constant string) or followed by an open parentheses (ie, a function name) will be
initially interpretted as a column name and its contents for the current row inserted into the
expression. If no such column exists, a keyword of that name will be searched for and its value
used, if found. To force the name to be interpretted as a keyword (in case there is both a column
and keyword with the same name), precede the keyword name with a single pound sign, '#', as in
'#NAXIS2'. Due to the generalities of FITS column and keyword names, if the column or keyword

4.2. DETAILED FILENAME SYNTAX 29
name contains a space or a character which might appear as an arithmetic term then inclose the
name in '$' characters as in $MAX PHA$ or #$MAX­PHA$. Names are case insensitive.
To access a table entry in a row other than the current one, follow the column's name with a
row offset within curly braces. For example, 'PHA­3' will evaluate to the value of column PHA, 3
rows above the row currently being processed. One cannot specify an absolute row number, only a
relative offset. Rows that fall outside the table will be treated as undefined, or NULLs.
Boolean operators can be used in the expression in either their Fortran or C forms. The following
boolean operators are available:
''equal'' .eq. .EQ. == ''not equal'' .ne. .NE. !=
''less than'' .lt. .LT. ! ''less than/equal'' .le. .LE. != =!
''greater than'' .gt. .GT. ? ''greater than/equal'' .ge. .GE. ?= =?
''or'' .or. .OR. ------ ''and'' .and. .AND. &&
''negation'' .not. .NOT. ! ''approx. equal(1e­7)'' ~
Note that the exclamation point, ' !', is a special UNIX character, so if it is used on the command
line rather than entered at a task prompt, it must be preceded by a backslash to force the UNIX
shell to ignore it.
The expression may also include arithmetic operators and functions. Trigonometric functions use
radians, not degrees. The following arithmetic operators and functions can be used in the expression
(function names are case insensitive):
''addition'' + ''subtraction'' ­
''multiplication'' * ''division'' /
''negation'' ­ ''exponentiation'' ** “
''absolute value'' abs(x) ''cosine'' cos(x)
''sine'' sin(x) ''tangent'' tan(x)
''arc cosine'' arccos(x) ''arc sine'' arcsin(x)
''arc tangent'' arctan(x) ''arc tangent'' arctan2(x,y)
''exponential'' exp(x) ''square root'' sqrt(x)
''natural log'' log(x) ''common log'' log10(x)
''modulus'' i % j ''random # [0.0,1.0)'' random()
''minimum'' min(x,y) ''maximum'' max(x,y)
An alternate syntax for the min and max functions has only a single argument which should be a
vector value (see below). The result will be the minimum/maximum element contained within the
vector.
Conditional arithmetic can be performed by multiplying, '*', boolean and arithmetic expressions
together. If the boolean subexpression evaluates to TRUE, the larger expression has the value
of the arithmetic subexpression. If the boolean is FALSE, the expression evaluates to zero. For
example, 7 \Lambda (5 ? 3) equals 7 whereas 7 \Lambda (5 ! 3) equals 0.
There are three functions that are primarily for use with SAO region files and the FSAOI task,

30 CHAPTER 4. EXTENDED FILE NAME SYNTAX
but they can be used directly. They return a boolean true or false depending on whether a two
dimensional point is in the region or not:
''point in a circular region''
circle(xcntr,ycntr,radius,Xcolumn,Ycolumn)
''point in an elliptical region''
ellipse(xcntr,ycntr,xhlf—wdth,yhlf—wdth,rotation,Xcolumn,Ycolumn)
''point in a rectangular region''
box(xcntr,ycntr,xfll—wdth,yfll—wdth,rotation,Xcolumn,Ycolumn)
where
(xcntr,ycntr) are the (x,y) position of the center of the region
(xhlf—wdth,yhlf—wdth) are the (x,y) half widths of the region
(xfll—wdth,yfll—wdth) are the (x,y) full widths of the region
(radius) is half the diameter of the circle
(rotation) is the angle(degrees) that the region is rotated with
respect to (xcntr,ycntr)
(Xcoord,Ycoord) are the (x,y) coordinates to test, usually column
names
NOTE: each parameter can itself be an expression, not merely a
column name or constant.
There is also a function for testing if two values are close to each other, i.e., if they are ''near'' each
other to within a user specified tolerance. The arguments, value 1 and value 2 can be integer or real
and represent the two values who's proximity is being tested to be within the specified tolerance,
also an integer or real:
near(value—1, value—2, tolerance)
When a NULL, or undefined, value is encountered in the FITS table, the expression will evalu­
ate to NULL unless the undefined value is not actually required for evaluation, eg. ''TRUE .or.
NULL'' evaluates to TRUE. The following two functions allow some NULL detection and handling:
ISNULL(x) and DEFNULL(x,y). The former returns a boolean value of TRUE if the argument x
is NULL. The later ''defines'' a value to be substituted for NULL values; it returns the value of x
if x is not NULL, otherwise it returns the value of y.
The following type casting operators are available, where the inclosing parentheses are required
and taken from the C language usage. Also, the integer to real casts values to double precision:
''real to integer'' (int) x (INT) x
''integer to real'' (float) i (FLOAT) i
Bit masks can be used to select out rows from bit columns (TFORMn = #X) in FITS files. To
represent the mask, binary, octal, and hex formats are allowed:

4.2. DETAILED FILENAME SYNTAX 31
binary: b0110xx1010000101xxxx0001
octal: o720x1 ­? (b111010000xxx001)
hex: h0FxD ­? (b00001111xxxx1101)
In all the representations, an x or X is allowed in the mask as a wild card. Note that the x represents
a different number of wild card bits in each representation. All representations are case insensitive.
To construct the boolean expression using the mask as the boolean equal operator discribed above
on a bit table column. For example, if you had a 7 bit column named flags in a FITS table and
wanted all rows having the bit pattern 0010011, the selection expression would be:
flags == b0010011
or
flags .eq. b10011
It is also possible to test if a range of bits is less than, less than equal, greater than and greater
than equal to a particular boolean value:
flags != bxxx010xx
flags .gt. bxxx100xx
flags .le. b1xxxxxxx
Notice the use of the x bit value to limit the range of bits being compared.
It is not necessary to specify the leading (most significant) zero (0) bits in the mask, as shown in
the second expression above.
Bit wise AND, OR and NOT operations are also possible on two or more bit fields using the
'&'(AND), 'j'(OR), and the ' !'(NOT) operators. All of these operators result in a bit field which
can then be used with the equal operator. For example:
(!flags) == b1101100
(flags & b1000001) == bx000001
Bit fields can be appended as well using the '+' operator. Strings can be concatenated this way,
too.
In addition, several constants are built in for use in numerical expressions:
#pi 3.1415... #e 2.7182...
#deg #pi/180 #row current row number
A string constant must be enclosed in quotes as in 'Crab'.
Vector Columns

32 CHAPTER 4. EXTENDED FILE NAME SYNTAX
Vector columns can also be used in building the expression. No special syntax is required if one
wants to operate on all elements of the vector. Simply use the column name as for a scalar
column. Vector columns can be freely intermixed with scalar columns or constants in virtually all
expressions. The result will be of the same dimension as the vector. Two vectors in an expression,
though, need to have the same number of elements and have the same dimensions. The only places
a vector column cannot be used (for now, anyway) are the SAO region functions and the NEAR
boolean function.
Arithmetic and logical operations are all performed on an element by element basis. Comparing two
vector columns, eg ''COL1 == COL2'', thus results in another vector of boolean values indicating
which elements of the two vectors are equal. Two functions are available which operate on vectors:
SUM(x) and NELEM(x). The former literally sums all the elements in x, returning a scalar value.
If x is a boolean vector, SUM returns the number of TRUE elements. The latter, NELEM, returns
the number of elements in vector x. (NELEM also operates on bit and string columns, returning
their column widths.) As an example, to test whether all elements of two vectors satisfy a given
logical comparison, one can use the expression
SUM( COL1 ? COL2 ) == NELEM( COL1 )
which will return TRUE if all elements of COL1 are greater than their corresponding elements in
COL2.
To specify a single element of a vector, give the column name followed by a comma­separated list
of coordinates enclosed in square brackets. For example, if a vector column named PHAS exists in
the table as a one dimensional, 256 component list of numbers from which you wanted to select the
57th component for use in the expression, then PHAS[57] would do the trick. Higher dimensional
arrays of data may appear in a column. But in order to interpret them, the TDIMn keyword
must appear in the header. Assuming that a (4,4,4,4) array is packed into each row of a column
named ARRAY4D, the (1,2,3,4) component element of each row is accessed by ARRAY4D[1,2,3,4].
Arrays up to dimension 5 are currently supported. Each vector index can itself be an expression,
although it must evaluate to an integer value within the bounds of the vector. Vector columns
which contain spaces or arithmetic operators must have their names enclosed in ''$'' characters as
with $ARRAY­4D$[1,2,3,4].
A more C­like syntax for specifying vector indices is also available. The element used in the
preceding example alternatively could be specified with the syntax ARRAY4D[4][3][2][1]. Note the
reverse order of indices (as in C), as well as the fact that the values are still ones­based (as in
Fortran -- adopted to avoid ambiguity for 1D vectors). With this syntax, one does not need to
specify all of the indices. To extract a 3D slice of this 4D array, use ARRAY4D[4].
Variable­length vector columns are not supported.
Vectors can be manually constructed within the expression using a comma­separated list of elements
surrounded by curly braces (''). For example, '1,3,6,1' is a 4­element vector containing the values
1, 3, 6, and 1. The vector can contain only boolean, integer, and real values (or expressions). The
elements will be promoted to the highest datatype present. Any elements which are themselves
vectors, will be expanded out with each of its elements becoming an element in the constructed
vector.

4.2. DETAILED FILENAME SYNTAX 33
A common filtering method applied to FITS files is a time filter using a Good Time Interval
(GTI) extension. A high­level function, gtifilter(a,b,c,d), is available which performs this special
evaluation, returning a boolean result for each time element tested. Its syntax is
gtifilter( [ ''filename'' [, expr [, ''STARTCOL'', ''STOPCOL'' ] ] ] )
where each ''[]'' demarks optional parameters. The filename, if specified, can be blank ('''') which
will mean to use the first extension with the name ''*GTI*'' in the current file, a plain extension
specifier (eg, ''+2'', ''[2]'', or ''[STDGTI]'') which will be used to select an extension in the current
file, or a regular filename with or without an extension specifier which in the latter case will mean
to use the first extension with an extension name ''*GTI*''. Expr can be any arithmetic expression,
including simply the time column name. A vector time expression will produce a vector boolean
result. STARTCOL and STOPCOL are the names of the START/STOP columns in the GTI
extension. If one of them is specified, they both must be. Note that the quotes surrounding the
filename and START/STOP column names are required.
In its simplest form, no parameters need to be provided -- default values will be used. The expression
''gtifilter()'' is equivalent to
gtifilter( '''', TIME, ''*START*'', ''*STOP*'' )
This will search the current file for a GTI extension, filter the TIME column in the current table,
using START/STOP times taken from columns in the GTI extension with names containing the
strings ''START'' and ''STOP''. The wildcards ('*') allow slight variations in naming conventions
such as ''TSTART'' or ''STARTTIME''. The same default values apply for unspecified parame­
ters when the first one or two parameters are specified. The function automatically searches for
TIMEZERO/I/F keywords in the current and GTI extensions, applying a relative time offset, if
necessary.
Another common filtering method is a spatial filter using a SAO­ style region file. The syntax for
this high­level filter is
regfilter( ''regfilename'' [ , Xexpr, Yexpr [ , ''wcs cols'' ] ] )
The region file name is required, but the rest is optional. Without any explicit expression for the
X and Y coordinates (in pixels), the filter will search for and operate on columns ''X'' and ''Y''.
If the region file is in ''degrees'' format instead of ''pixels'' (''hhmmss'' format is not supported,
yet), the filter will need WCS information to convert the region coordinates to pixels. If supplied,
the final parameter string contains the names of the 2 columns (space or comma separated) which
contain the desired WCS information. If not supplied, the filter will scan the X and Y expressions
for column names. If only one is found in each expression, those columns will be used. Otherwise,
an error will be returned.
The region shapes supported are (names are case insensitive):

34 CHAPTER 4. EXTENDED FILE NAME SYNTAX
Point ( X1, Y1 ) !­ One pixel square region
Line ( X1, Y1, X2, Y2 ) !­ One pixel wide region
Polygon ( X1, Y1, X2, Y2, ... ) !­ Rest are interiors with
Rectangle ( X1, Y1, X2, Y2, A ) --- boundaries considered
Box ( Xc, Yc, Wdth, Hght, A ) V within the region
Diamond ( Xc, Yc, Wdth, Hght, A )
Circle ( Xc, Yc, R )
Annulus ( Xc, Yc, Rin, Rout )
Ellipse ( Xc, Yc, Rx, Ry, A )
Elliptannulus ( Xc, Yc, Rinx, Riny, Routx, Routy, Ain, Aout )
Sector ( Xc, Yc, Amin, Amax )
where (Xc,Yc) is the coordinate of the shape's center; (X#,Y#) are the coordinates of the shape's
edges; Rxxx are the shapes' various Radii or semimajor/minor axes; and Axxx are the angles of
rotation (or bounding angles for Sector) in degrees. For rotated shapes, the rotation angle can be
left off, indicating no rotation. Common alternate names for the regions can also be used: rotbox
== box; rotrectangle == rectangle; (rot)rhombus == (rot)diamond; and pie == sector. When a
shape's name is preceded by a minus sign, '­', the defined region is instead the area *outside* its
boundary (ie, the region is inverted). All the shapes within a single region file are AND'd together
to create the region.
For complex or commonly used filters, one can also place the expression into a text file and import
it into the row filter using the syntax '[@filename.txt]'. The expression can be arbitrarily complex
and extend over multiple lines of the file.
EXAMPLES:
[ binary && mag != 5.0] ­ Extract all binary stars brighter
than fifth magnitude (note that
the initial space is necessary to
prevent it from being treated as a
binning specification)
[#row ?= 125 && #row != 175] ­ Extract row numbers 125 through 175
[IMAGE[4,5] .gt. 100] ­ Extract all rows that have the
(4,5) component of the IMAGE column
greater than 100
[abs(sin(theta * #deg)) ! 0.5] ­ Extract all rows having the
absolute value of the sine of theta
less than a half where the angles
are tabulated in degrees
[SUM( SPEC ? 3*BACKGRND )?=1] ­ Extract all rows containing a
spectrum, held in vector column

4.2. DETAILED FILENAME SYNTAX 35
SPEC, with at least one value 3
times greater than the background
level held in a keyword, BACKGRND
[VCOL==--1,4,2ť] ­ Extract all rows whose vector column
VCOL contains the 3­elements 1, 4, and
2.
[@rowFilter.txt] ­ Extract rows using the expression
contained within the text file
rowFilter.txt
4.2.9 Binning or Histogramming Specification
The optional binning specifier is enclosed in square brackets and can be distinguished from a
general row filter specification by the fact that it begins with the keyword 'bin' not immediately
followed by an equals sign. When binning is specfied, a temporary N­dimensional FITS primary
array is created by computing the histogram of the values in the specified columns of a FITS table
extension. After the histogram is computed the input FITS file containing the table is then closed
and the temporary FITS primary array is opened and passed to the application program. Thus,
the application program never sees the original FITS table and only sees the image in the new
temporary file (which has no additional extensions). Obviously, the application program must be
expecting to open a FITS image and not a FITS table in this case.
The data type of the FITS histogram image may be specified by appending 'b' (for 8­bit byte), 'i'
(for 16­bit integers), 'j' (for 32­bit integer), 'r' (for 32­bit floating points), or 'd' (for 64­bit double
precision floating point) to the 'bin' keyword (e.g. '[binr X]' creates a real floating point image). If
the datatype is not explicitly specified then a 32­bit integer image will be created by default, unless
the weighting option is also specified in which case the image will have a 32­bit floating point data
type by default.
The histogram image may have from 1 to 4 dimensions (axes), depending on the number of columns
that are specified. The general form of the binning specification is:
[bin--bijrdť Xcol=min:max:binsize, Ycol= ..., Zcol=..., Tcol=...; weight]
in which up to 4 columns, each corresponding to an axis of the image, are listed. The column
names are case insensitive, and the column number may be given instead of the name, preceded by
a pound sign (e.g., [bin #4=1:512]). If the column name is not specified, then CFITSIO will first
try to use the 'preferred column' as specified by the CPREF keyword if it exists (e.g., 'CPREF =
'DETX,DETY'), otherwise column names 'X', 'Y', 'Z', and 'T' will be assumed for each of the 4
axes, respectively.
Each column name may be followed by an equals sign and then the lower and upper range of the
histogram, and the size of the histogram bins, separated by colons. Spaces are allowed before and
after the equals sign but not within the 'min:max:binsize' string. The min, max and binsize values

36 CHAPTER 4. EXTENDED FILE NAME SYNTAX
may be integer or floating point numbers, or they may be the names of keywords in the header of
the table. If the latter, then the value of that keyword is substituted into the expression.
Default values for the min, max and binsize quantities will be used if not explicitly given in the
binning expression as shown in these examples:
[bin x = :512:2] ­ use default minimum value
[bin x = 1::2] ­ use default maximum value
[bin x = 1:512] ­ use default bin size
[bin x = 1:] ­ use default maximum value and bin size
[bin x = :512] ­ use default minimum value and bin size
[bin x = 2] ­ use default minimum and maximum values
[bin x] ­ use default minimum, maximum and bin size
[bin 4] ­ default 2­D image, bin size = 4 in both axes
[bin] ­ default 2­D image
CFITSIO will use the value of the TLMINn, TLMAXn, and TDBINn keywords, if they exist, for
the default min, max, and binsize, respectively. If they do not exist then CFITSIO will use the
actual minimum and maximum values in the column for the histogram min and max values. The
default binsize will be set to 1, or (max ­ min) / 10., whichever is smaller, so that the histogram
will have at least 10 bins along each axis.
A shortcut notation is allowed if all the columns/axes have the same binning specification. In
this case all the column names may be listed within parentheses, followed by the (single) binning
specification, as in:
[bin (X,Y)=1:512:2]
[bin (X,Y) = 5]
The optional weighting factor is the last item in the binning specifier and, if present, is separated
from the list of columns by a semi­colon. As the histogram is accumulated, this weight is used
to incremented the value of the appropriated bin in the histogram. If the weighting factor is not
specified, then the default weight = 1 is assumed. The weighting factor may be a constant integer or
floating point number, or the name of a keyword containing the weighting value. Or the weighting
factor may be the name of a table column in which case the value in that column, on a row by row
basis, will be used.
In some cases, the column or keyword may give the reciprocal of the actual weight value that is
needed. In this case, precede the weight keyword or column name by a slash '/' to tell CFITSIO
to use the reciprocal of the value when constructing the histogram.
For complex or commonly used histograms, one can also place its description into a text file and
import it into the binning specification using the syntax '[binbijrd @filename.txt]'. The file's con­
tents can extend over multiple lines, although it must still conform to the no­spaces rule for the
min:max:binsize syntax and each axis specification must still be comma­separated.
Examples:

4.2. DETAILED FILENAME SYNTAX 37
[bini detx, dety] ­ 2­D, 16­bit integer histogram
of DETX and DETY columns, using
default values for the histogram
range and binsize
[bin (detx, dety)=16; /exposure] ­ 2­D, 32­bit real histogram of DETX
and DETY columns with a bin size = 16
in both axes. The histogram values
are divided by the EXPOSURE keyword
value.
[bin time=TSTART:TSTOP:0.1] ­ 1­D lightcurve, range determined by
the TSTART and TSTOP keywords,
with 0.1 unit size bins.
[bin pha, time=8000.:8100.:0.1] ­ 2­D image using default binning
of the PHA column for the X axis,
and 1000 bins in the range
8000. to 8100. for the Y axis.
[bin @binFilter.txt] ­ Use the contents of the text file
binFilter.txt for the binning
specifications.

38 CHAPTER 4. EXTENDED FILE NAME SYNTAX

Chapter 5
CFITSIO Conventions and Guidelines
5.1 CFITSIO Definitions
Any program that uses the CFITSIO interface must include the fitsio.h header file with the state­
ment
#include ''fitsio.h''
This header file contains the prototypes for all the CFITSIO user interface routines as well as the
definitions of various constants used in the interface. It also defines a C structure of type `fitsfile'
that is used by CFITSIO to store the relevant parameters that define the format of a particular
FITS file. Application programs must define a pointer to this structure for each FITS file that is
to be opened. This structure is initialized (i.e., memory is allocated for the structure) when the
FITS file is first opened or created with the fits open file or fits create file routines. This fitsfile
pointer is then passed as the first argument to every other CFITSIO routine that operates on the
FITS file. Application programs must not directly read or write elements in this fitsfile structure
because the definition of the structure may change in future versions of CFITSIO.
A number of symbolic constants are also defined in fitsio.h for the convenience of application
programmers. Use of these symbolic constants rather than the actual numeric value will help to
make the source code more readable and easier for others to understand.
String Lengths, for use when allocating character arrays:
#define FLEN—FILENAME 1025 /* max length of a filename */
#define FLEN—KEYWORD 72 /* max length of a keyword */
#define FLEN—CARD 81 /* max length of a FITS header card */
#define FLEN—VALUE 71 /* max length of a keyword value string */
#define FLEN—COMMENT 73 /* max length of a keyword comment string */
#define FLEN—ERRMSG 81 /* max length of a CFITSIO error message */
#define FLEN—STATUS 31 /* max length of a CFITSIO status text string */
39

40 CHAPTER 5. CFITSIO CONVENTIONS AND GUIDELINES
Note that FLEN—KEYWORD is longer than the nominal 8­character keyword
name length because the HIERARCH convention supports longer keyword names.
Access modes when opening a FITS file:
#define READONLY 0
#define READWRITE 1
BITPIX data type code values for FITS images:
#define BYTE—IMG 8 /* 8­bit unsigned integers */
#define SHORT—IMG 16 /* 16­bit signed integers */
#define LONG—IMG 32 /* 32­bit signed integers */
#define FLOAT—IMG ­32 /* 32­bit single precision floating point */
#define DOUBLE—IMG ­64 /* 64­bit double precision floating point */
The following 2 data type codes are also supported by CFITSIO:
#define USHORT—IMG 20 /* 16­bit unsigned integers, equivalent to */
/* BITPIX = 16, BSCALE = 1, BZERO = 32768 */
#define ULONG—IMG 40 /* 32­bit unsigned integers, equivalent to */
/* BITPIX = 32, BSCALE = 1, BZERO = 2147483648 */
Codes for the datatype of binary table columns and/or for the
datatype of variables when reading or writing keywords or data:
DATATYPE TFORM CODE
#define TBIT 1 /* 'X' */
#define TBYTE 11 /* 8­bit unsigned byte, 'B' */
#define TLOGICAL 14 /* logicals (int for keywords */
/* and char for table cols 'L' */
#define TSTRING 16 /* ASCII string, 'A' */
#define TSHORT 21 /* signed short, 'I' */
#define TLONG 41 /* signed long, 'J' */
#define TFLOAT 42 /* single precision float, 'E' */
#define TDOUBLE 82 /* double precision float, 'D' */
#define TCOMPLEX 83 /* complex (pair of floats) 'C' */
#define TDBLCOMPLEX 163 /* double complex (2 doubles) 'M' */
The following data type codes are also supported by CFITSIO:
#define TINT 31 /* int */
#define TUINT 30 /* unsigned int */
#define TUSHORT 20 /* unsigned short */
#define TULONG 40 /* unsigned long */

5.2. CFITSIO SIZE LIMITATIONS 41
HDU type code values (value returned when moving to new HDU):
#define IMAGE—HDU 0 /* Primary Array or IMAGE HDU */
#define ASCII—TBL 1 /* ASCII table HDU */
#define BINARY—TBL 2 /* Binary table HDU */
#define ANY—HDU ­1 /* matches any type of HDU */
Column name and string matching case­sensitivity:
#define CASESEN 1 /* do case­sensitive string match */
#define CASEINSEN 0 /* do case­insensitive string match */
Logical states (if TRUE and FALSE are not already defined):
#define TRUE 1
#define FALSE 0
Values to represent undefined floating point numbers:
#define FLOATNULLVALUE ­9.11E­36F
#define DOUBLENULLVALUE ­9.11E­36L
5.2 CFITSIO Size Limitations
In general, CFITSIO places no limits on the sizes of the FITS files that it reads or writes. There
is no internal limit on the size of the dimensions of the primary array or IMAGE extension. Table
extensions may have up to 999 columns (the maximum allowed by the FITS standard) and may
have an arbitrarily large number of rows. There are a few other limits, however, which may affect
some extreme cases:
1. The maximum number of files that may be simultaneously opened is limited to the number of
internal IO buffers allocated in CFITSIO (currently 25, as defined by NIOBUF in the file fitsio2.h),
or by the limit of the underlying C compiler or machine operating system, which ever is smaller.
The C symbolic constant FOPEN MAX usually defines the total number of files that may open at
once (this includes any other text or binary files which may be open, not just FITS files).
2. The maximum number of extensions that can be read or written in a single FITS file is currently
set to 1000 as defined by MAXHDU in the fitsio.h file. This value may be increased if necessary,
but the access times to the later extensions in such files may become very long.
3. CFITSIO can handle FITS files up to about 2.1 GB in size which is the maximum value of a
32­bit signed long integer. Some machines that use 8­byte words for a long integer may support
larger files, but this has not been tested.

42 CHAPTER 5. CFITSIO CONVENTIONS AND GUIDELINES
5.3 Multiple Access to the Same FITS File
CFITSIO supports simultaneous read and write access to multiple HDUs in the same FITS file.
Thus, one can open the same FITS file twice within a single program and move to 2 different
HDUs in the file, and then read and write data or keywords to the 2 extensions just as if one were
accessing 2 completely separate FITS files. Since in general it is not possible to physically open the
same file twice and then expect to be able to simultaneously (or in alternating succession) write
to 2 different locations in the file, CFITSIO recognizes when the file to be opened (in the call to
fits open file) has already been opened and instead of actually opening the file again, just logically
links the new file to the old file. (This only applies if the file is opened more than once within the
same program, and does not prevent the same file from being simultaneously opened by more than
one program). Then before CFITSIO reads or writes to either (logical) file, it makes sure that any
modifications made to the other file have been completely flushed from the internal buffers to the
file. Thus, in principle, one could open a file twice, in one case pointing to the first extension and
in the other pointing to the 2nd extension and then write data to both extensions, in any order,
without danger of corrupting the file, There may be some efficiency penalties in doing this however,
since CFITSIO has to flush all the internal buffers related to one file before switching to the other,
so it would still be prudent to minimize the number of times one switches back and forth between
doing I/O to different HDUs in the same file.
5.4 Current Header Data Unit (CHDU)
In general, a FITS file can contain multiple Header Data Units, also called extensions. CFITSIO
only operates within one HDU at any given time, and the currently selected HDU is called the
Current Header Data Unit (CHDU). When a FITS file is first created or opened the CHDU is
automatically defined to be the first HDU (i.e., the primary array). CFITSIO routines are provided
to move to and open any other existing HDU within the FITS file or to append or insert a new
HDU in the FITS file which then becomes the CHDU.
5.5 Function Names and Datatypes
All the CFITSIO functions have both a short name as well as a longer descriptive name. The short
name is only 5 or 6 characters long and is similar to the subroutine name in the Fortran­77 version
of FITSIO. The longer name is more descriptive and it is recommended that it be used instead of
the short name to more clearly document the source code.
Many of the CFITSIO routines come in families which differ only in the datatype of the associated
parameter(s). The datatype of these routines is indicated by the suffix of the routine name. The
short routine names have a 1 or 2 character suffix (e.g., 'j' in 'ffpkyj') while the long routine names
have a 4 character or longer suffix as shown in the following table:
Long Short Data
Names Names Type

5.5. FUNCTION NAMES AND DATATYPES 43
­­­­­ ­­­­­ ­­­­
—bit x bit
—byt b unsigned byte
—sht i short integer
—lng j long integer
—usht ui unsigned short integer
—ulng uj unsigned long integer
—uint uk unsigned int integer
—int k int integer
—flt e real exponential floating point (float)
—fixflt f real fixed­decimal format floating point (float)
—dbl d double precision real floating­point (double)
—fixdbl g double precision fixed­format floating point (double)
—cmp c complex reals (pairs of float values)
—fixcmp fc complex reals, fixed­format floating point
—dblcmp m double precision complex (pairs of double values)
—fixdblcmp fm double precision complex, fixed­format floating point
—log l logical (int)
—str s character string
The logical datatype corresponds to `int' for logical keyword values, and `byte' for logical binary
table columns. In otherwords, the value when writing a logical keyword must be stored in an
`int' variable, and must be stored in a `char' array when reading or writing to `L' columns in a
binary table. Inplicit data type conversion is not supported for logical table columns, but is for
keywords, so a logical keyword may be read and cast to any numerical data type; a returned value
= 0 indicates false, and any other value = true.
The `int' datatype may be 2 bytes long on some IBM PC compatible systems and is usually 4 bytes
long on most other systems. Some 64­bit machines, however, like the Dec Alpha/OSF, define the
`short', `int', and `long' integer datatypes to be 2, 4, and 8 bytes long, respectively. The FITS
standard only supports 2 and 4 byte integer data types, so CFITSIO internally converts between
4 and 8 bytes when reading or writing `long' integers on Alpha/OSF systems.
When dealing with the FITS byte datatype it is important to remember that the raw values (before
any scaling by the BSCALE and BZERO, or TSCALn and TZEROn keyword values) in byte arrays
(BITPIX = 8) or byte columns (TFORMn = 'B') are interpreted as unsigned bytes with values
ranging from 0 to 255. Some C compilers define a 'char' variable as signed, so it is important to
explicitly declare a numeric char variable as 'unsigned char' to avoid any ambiguity
One feature of the CFITSIO routines is that they can operate on a `X' (bit) column in a binary table
as though it were a `B' (byte) column. For example a `11X' datatype column can be interpreted
the same as a `2B' column (i.e., 2 unsigned 8­bit bytes). In some instances, it can be more efficient
to read and write whole bytes at a time, rather than reading or writing each individual bit.
The complex and double precision complex datatypes are not directly supported in ANSI C so
these datatypes should be interpreted as pairs of float or double values, respectively, where the first
value in each pair is the real part, and the second is the imaginary part.

44 CHAPTER 5. CFITSIO CONVENTIONS AND GUIDELINES
5.6 Unsigned Integers
Although FITS does not directly support unsigned integers as one of its fundamental datatypes,
FITS can still be used to efficiently store unsigned integer data values in images and binary tables.
The convention used in FITS files is to store the unsigned integers as signed integers with an
associated offset (specified by the BZERO or TZEROn keyword). For example, to store unsigned
16­bit integer values in a FITS image the image would be defined as a signed 16­bit integer (with
BITPIX keyword = SHORT IMG = 16) with the keywords BSCALE = 1.0 and BZERO = 32768.
Thus the unsigned values of 0, 32768, and 65535, for example, are physically stored in the FITS
image as ­32768, 0, and 32767, respectively; CFITSIO automatically adds the BZERO offset to
these values when they are read. Similarly, in the case of unsigned 32­bit integers the BITPIX
keyword would be equal to LONG IMG = 32 and BZERO would be equal to 2147483648 (i.e. 2
raised to the 31st power).
The CFITSIO interface routines will efficiently and transparently apply the appropriate offset in
these cases so in general application programs do not need to be concerned with how the unsigned
values are actually stored in the FITS file. As a convenience for users, CFITSIO has several
predefined constants for the value of BITPIX (USHORT IMG, ULONG IMG) and for the TFORMn
value in the case of binary tables (`U' and `V') which programmers can use when creating FITS
files containing unsigned integer values. The following code fragment illustrates how to write a
FITS 1­D primary array of unsigned 16­bit integers:
unsigned short uarray[100];
int naxis, status;
long naxes[10], group, firstelem, nelements;
...
status = 0;
naxis = 1;
naxes[0] = 100;
fits—create—img(fptr, USHORT—IMG, naxis, naxes, &status);
firstelem = 1;
nelements = 100;
fits—write—img(fptr, TUSHORT, firstelem, nelements,
uarray, &status);
...
In the above example, the 2nd parameter in fits create img tells CFITSIO to write the header
keywords appropriate for an array of 16­bit unsigned integers (i.e., BITPIX = 16 and BZERO =
32768). Then the fits write img routine writes the array of unsigned short integers (uarray) into the
primary array of the FITS file. Similarly, a 32­bit unsigned integer image may be created by setting
the second parameter in fits create img equal to `ULONG IMG' and by calling the fits write img
routine with the second parameter = TULONG to write the array of unsigned long image pixel
values.
An analogous set of routines are available for reading or writing unsigned integer values in a FITS

5.6. UNSIGNED INTEGERS 45
binary table extension. When specifying the TFORMn keyword value which defines the format of
a column, CFITSIO recognized 2 additional datatype codes besides those already defined in the
FITS standard: `U' meaning a 16­bit unsigned integer column, and `V' for a 32­bit unsigned integer
column. These non­standard datatype codes are not actually written into the FITS file but instead
are just used internally within CFITSIO. The following code fragment illustrates how to use these
features:
unsigned short uarray[100];
unsigned int varray[100];
int colnum, tfields, status;
long nrows, firstrow, firstelem, nelements, pcount;
char extname[] = ''Test—table''; /* extension name */
/* define the name, datatype, and physical units for the 2 columns */
char *ttype[] = -- ''Col—1'', ''Col—2'' ť;
char *tform[] = -- ''1U'', ''1V'' ť; /* special CFITSIO codes */
char *tunit[] = -- '' '', '' '' ť;
...
/* write the header keywords */
status = 0;
nrows = 1;
tfields = 2
pcount = 0;
fits—create—tbl(fptr, BINARY—TBL, nrows, tfields, ttype, tform,
tunit, extname, &status);
/* write the unsigned shorts to the 1st column */
colnum = 1;
firstrow = 1;
firstelem = 1;
nelements = 100;
fits—write—col(fptr, TUSHORT, colnum, firstrow, firstelem,
nelements, uarray, &status);
/* now write the unsigned longs to the 2nd column */
colnum = 2;
fits—write—col(fptr, TUINT, colnum, firstrow, firstelem,
nelements, varray, &status);
...
Note that the non­standard TFORM values for the 2 columns, `U' and `V', tell CFITSIO to write the
keywords appropriate for unsigned 16­bit and unsigned 32­bit integers, respectively (i.e., TFORMn

46 CHAPTER 5. CFITSIO CONVENTIONS AND GUIDELINES
= '1I' and TZEROn = 32678 for unsigned 16­bit integers, and TFORMn = '1J' and TZEROn
= 2147483648 for unsigned 32­bit integers). The calls to fits write col then write the arrays of
unsigned integer values to the columns.
5.7 Character Strings
The character string values in a FITS header or in an ASCII column in a FITS table extension
are generally padded out with non­significant space characters (ASCII 32) to fill up the header
record or the column width. When reading a FITS string value, the CFITSIO routines will strip
off these non­significant trailing spaces and will return a null­terminated string value containing
only the significant characters. Leading spaces in a FITS string are considered significant. If the
string contains all blanks, then CFITSIO will return a single blank character, i.e, the first blank
is considered to be significant, since it distinquishes the string from a null or undefined string, but
the remaining trailing spaces are not significant.
Similarly, when writing string values to a FITS file the CFITSIO routines expect to get a null­
terminated string as input; CFITSIO will pad the string with blanks if necessary when writing it
to the FITS file.
When calling CFITSIO routines that return a character string it is vital that the size of the char
array be large enough to hold the entire string of characters, otherwise CFITSIO will overwrite
whatever memory locations follow the char array, possibly causing the program to execute incor­
rectly. This type of error can be difficult to debug, so programmers should always ensure that the
char arrays are allocated enough space to hold the longest possible string, including the terminat­
ing NULL character. The fitsio.h file contains the following defined constants which programmers
are strongly encouraged to use whenever they are allocating space for char arrays:
#define FLEN—FILENAME 1025 /* max length of a filename */
#define FLEN—KEYWORD 72 /* max length of a keyword */
#define FLEN—CARD 81 /* length of a FITS header card */
#define FLEN—VALUE 71 /* max length of a keyword value string */
#define FLEN—COMMENT 73 /* max length of a keyword comment string */
#define FLEN—ERRMSG 81 /* max length of a CFITSIO error message */
#define FLEN—STATUS 31 /* max length of a CFITSIO status text string */
For example, when declaring a char array to hold the value string of FITS keyword, use the following
statement:
char value[FLEN—VALUE];
Note that FLEN KEYWORD is longer than needed for the nominal 8­character keyword name
because the HIERARCH convention supports longer keyword names.

5.8. IMPLICIT DATA TYPE CONVERSION 47
5.8 Implicit Data Type Conversion
The CFITSIO routines that read and write numerical data can perform implicit data type con­
version. This means that the data type of the variable or array in the program does not need to
be the same as the data type of the value in the FITS file. Data type conversion is supported
for numerical data types when reading a FITS header keyword value and when reading or writing
values in the primary array or a table column. CFITSIO returns status = NUM OVERFLOW if
the converted data value exceeds the range of the output data type. Implicit data type conversion
is not supported for string, logical, complex, or double complex data types.
5.9 Data Scaling
When reading numerical data values in the primary array or a table column, the values will be
scaled automatically by the BSCALE and BZERO (or TSCALn and TZEROn) header values if
they are present in the header. The scaled data that is returned to the reading program will have
output value = (FITS value) * BSCALE + BZERO
(a corresponding formula using TSCALn and TZEROn is used when reading from table columns).
In the case of integer output values the floating point scaled value is truncated to an integer (not
rounded to the nearest integer). The fits set bscale and fits set tscale routines (described in the
`Advanced' chapter) may be used to override the scaling parameters defined in the header (e.g., to
turn off the scaling so that the program can read the raw unscaled values from the FITS file).
When writing numerical data to the primary array or to a table column the data values will
generally be automatically inversely scaled by the value of the BSCALE and BZERO (or TSCALn
and TZEROn) keyword values if they they exist in the header. These keywords must have been
written to the header before any data is written for them to have any immediate effect. One may
also use the fits set bscale and fits set tscale routines to define or override the scaling keywords in
the header (e.g., to turn off the scaling so that the program can write the raw unscaled values into
the FITS file). If scaling is performed, the inverse scaled output value that is written into the FITS
file will have
FITS value = ((input value) ­ BZERO) / BSCALE
(a corresponding formula using TSCALn and TZEROn is used when writing to table columns).
Rounding to the nearest integer, rather than truncation, is performed when writing integer datatypes
to the FITS file.
5.10 Error Status Values and the Error Message Stack
Nearly all the CFITSIO routines return an error status value in 2 ways: as the value of the last
parameter in the function call, and as the returned value of the function itself. This provides some

48 CHAPTER 5. CFITSIO CONVENTIONS AND GUIDELINES
flexibility in the way programmers can test if an error occurred, as illustrated in the following 2
code fragments:
if ( fits—write—record(fptr, card, &status) )
printf('' Error occurred while writing keyword.'');
or,
fits—write—record(fptr, card, &status);
if ( status )
printf('' Error occurred while writing keyword.'');
A listing of all the CFITSIO status code values is given at the end of this document. Programmers
are encouraged to use the symbolic mnemonics (defined in fitsio.h) rather than the actual integer
status values to improve the readability of their code.
The CFITSIO library uses an `inherited status' convention for the status parameter which means
that if a routine is called with a positive input value of the status parameter as input, then the
routine will exit immediately without changing the value of the status parameter. Thus, if one
passes the status value returned from each CFITSIO routine as input to the next CFITSIO routine,
then whenever an error is detected all further CFITSIO processing will cease. This convention can
simplify the error checking in application programs because it is not necessary to check the value
of the status parameter after every single CFITSIO routine call. If a program contains a sequence
of several CFITSIO calls, one can just check the status value after the last call. Since the returned
status values are generally distinctive, it should be possible to determine which routine originally
returned the error status.
CFITSIO also maintains an internal stack of error messages (80­character maximum length) which
in many cases provide a more detailed explanation of the cause of the error than is provided by
the error status number alone. It is recommended that the error message stack be printed out
whenever a program detects a CFITSIO error. The function fits report error will print out the
entire error message stack, or alternatively one may call fits read errmsg to get the error messages
one at a time.
5.11 Variable­Length Arrays in Binary Tables
CFITSIO provides easy­to­use support for reading and writing data in variable length fields of a
binary table. The variable length columns have TFORMn keyword values of the form `1Pt(len)'
where `t' is the datatype code (e.g., I, J, E, D, etc.) and `len' is an integer specifying the maximum
length of the vector in the table. If the value of `len' is not specified when the table is created (e.g.,
if the TFORM keyword value is simply specified as '1PE' instead of '1PE(400) ), then CFITSIO
will automatically scan the table when it is closed to determine the maximum length of the vector
and will append this value to the TFORMn value.

5.11. VARIABLE­LENGTH ARRAYS IN BINARY TABLES 49
The same routines which read and write data in an ordinary fixed length binary table extension
are also used for variable length fields, however, the routine parameters take on a slightly different
interpretation as described below.
All the data in a variable length field is written into an area called the `heap' which follows the
main fixed­length FITS binary table. The size of the heap, in bytes, is specified by the PCOUNT
keyword in the FITS header. When creating a new binary table, the initial value of PCOUNT should
usually be set to zero. CFITSIO will recompute the size of the heap as the data is written and will
automatically update the PCOUNT keyword value when the table is closed. When writing variable
length data to a table, CFITSIO will automatically extend the size of the heap area if necessary,
so that any following HDUs do not get overwritten.
By default the heap data area starts immediately after the last row of the fixed­length table. This
default starting location may be overridden by the THEAP keyword, but this is not recommended.
If addtional rows of data are added to the table, CFITSIO will automatically shift the the heap
down to make room for the new rows, but it is obviously be more efficient to initially create the
table with the necessary number of blank rows, so that the heap does not needed to be constantly
moved.
When writing to a variable length field the entire array of values for a given row of the table must
be written with a single call to fits write col. The total length of the array is given by nelements +
firstelem ­ 1. Additional elements cannot be appended to an existing vector at a later time since
any attempt to do so will simply overwrite all the previously written data. Note also that the new
data will be written to a new area of the heap and the heap space used by the previous write cannot
be reclaimed. For this reason each row of a variable length field should only be written once. An
exception to this general rule occurs when setting elements of an array as undefined. One must
first write a dummy value into the array with fits write col, and then call fits write col nul to flag
the desired elements as undefined. (Do not use the fits write colnul routines with variable length
fields). Note that the rows of a table, whether fixed or variable length, do not have to be written
consecutively and may be written in any order.
When writing to a variable length ASCII character field (e.g., TFORM = '1PA') only a single
character string can be written. The `firstelem' and `nelements' parameter values in the fits write col
routine are ignored and the number of characters to write is simply determined by the length of
the input null­terminated character string.
The fits write descript routine is useful in situations where multiple rows of a variable length column
have the identical array of values. One can simply write the array once for the first row, and then
use fits write descript to write the same descriptor values into the other rows; all the rows will then
point to the same storage location thus saving disk space.
When reading from a variable length array field one can only read as many elements as actually
exist in that row of the table; reading does not automatically continue with the next row of the
table as occurs when reading an ordinary fixed length table field. Attempts to read more than this
will cause an error status to be returned. One can determine the number of elements in each row
of a variable column with the fits read descript routine.

50 CHAPTER 5. CFITSIO CONVENTIONS AND GUIDELINES
5.12 Support for IEEE Special Values
The ANSI/IEEE­754 floating­point number standard defines certain special values that are used to
represent such quantities as Not­a­Number (NaN), denormalized, underflow, overflow, and infinity.
(See the Appendix in the NOST FITS standard or the NOST FITS User's Guide for a list of these
values). The CFITSIO routines that read floating point data in FITS files recognize these IEEE
special values and by default interpret the overflow and infinity values as being equivalent to a NaN,
and convert the underflow and denormalized values into zeros. In some cases programmers may
want access to the raw IEEE values, without any modification by CFITSIO. This can be done by
calling the fits read img or fits read col routines while specifying 0.0 as the value of the NULLVAL
parameter. This will force CFITSIO to simply pass the IEEE values through to the application
program without any modification. This is not fully supported on VAX/VMS machines, however,
where there is no easy way to bypass the default interpretation of the IEEE special values.
5.13 When the Final Size of the FITS HDU is Unknown
It is not required to know the total size of a FITS data array or table before beginning to write the
data to the FITS file. In the case of the primary array or an image extension, one should initially
create the array with the size of the highest dimension (largest NAXISn keyword) set to a dummy
value, such as 1. Then after all the data have been written and the true dimensions are known, then
the NAXISn value should be updated using the fits update key routine before moving to another
extension or closing the FITS file.
When writing to FITS tables, CFITSIO automatically keeps track of the highest row number that
is written to, and will increase the size of the table if necessary. CFITSIO will also automatically
insert space in the FITS file if necessary, to ensure that the data 'heap', if it exists, and/or any
additional HDUs that follow the table do not get overwritten as new rows are written to the table.
As a general rule it is best to specify the initial number of rows = 0 when the table is created,
then let CFITSIO keep track of the number of rows that are actually written. The application
program should not manually update the number of rows in the table (as given by the NAXIS2
keyword) since CFITSIO does this automatically. If a table is initially created with more than
zero rows, then this will ususally be considered as the minimum size of the table, even if fewer
rows are actually written to the table. Thus, if a table is initially created with NAXIS2 = 20, and
CFITSIO only writes 10 rows of data before closing the table, then NAXIS2 will remain equal to
20. If however, 30 rows of data are written to this table, then NAXIS2 will be increased from 20
to 30. The one exception to this automatic updating of the NAXIS2 keyword is if the application
program directly modifies the value of NAXIS2 (up or down) itself just before closing the table. In
this case, CFITSIO does not update NAXIS2 again, since it assumes that the application program
must have had a good reason for changing the value directly. This is not recommended, however,
and is only provided for backward compatibility with software that initially creates a table with
a large number of rows, than decreases the NAXIS2 value to the actual smaller value just before
closing the table.

5.14. LOCAL FITS CONVENTIONS SUPPORTED BY CFITSIO 51
5.14 Local FITS Conventions supported by CFITSIO
In a few cases CFITSIO supports local FITS conventions which are not defined in the official NOST
FITS standard and which are not necessarily recognized or supported by other FITS software
packages. Programmers should be cautious about using these features, especially if the FITS files
that are produced are expected to be processed by other software systems which do not use the
CFITSIO interface.
5.14.1 Long String Keyword Values.
The length of a standard FITS string keyword is limited to 68 characters because it must fit
entirely within a single FITS header keyword record. In some instances it is necessary to encode
strings longer than this limit, so CFITSIO supports a local convention in which the string value is
continued over multiple keywords. This continuation convention uses an ampersand character at
the end of each substring to indicate that it is continued on the next keyword, and the continuation
keywords all have the name CONTINUE without an equal sign in column 9. The string value
may be continued in this way over as many additional CONTINUE keywords as is required. The
following lines illustrate this continuation convention which is used in the value of the STRKEY
keyword:
LONGSTRN= 'OGIP 1.0' / The OGIP Long String Convention may be used.
STRKEY = 'This is a very long string keyword&' / Optional Comment
CONTINUE ' value that is continued over 3 keywords in the & '
CONTINUE 'FITS header.' / This is another optional comment.
It is recommended that the LONGSTRN keyword, as shown here, always be included in any HDU
that uses this longstring convention as a warning to any software that must read the keywords. A
routine called fits write key longwarn has been provided in CFITSIO to write this keyword if it
does not already exist.
This long string convention is supported by the following CFITSIO routines:
fits—write—key—longstr ­ write a long string keyword value
fits—insert—key—longstr ­ insert a long string keyword value
fits—modify—key—longstr ­ modify a long string keyword value
fits—update—key—longstr ­ modify a long string keyword value
fits—read—key—longstr ­ read a long string keyword value
fits—delete—key ­ delete a keyword
The fits read key longstr routine is unique among all the CFITSIO routines in that it internally
allocates memory for the long string value; all the other CFITSIO routines that deal with arrays
require that the calling program pre­allocate adequate space to hold the array of data. Conse­
quently, programs which use the fits read key longstr routine must be careful to free the allocated
memory for the string when it is no longer needed.
The following 2 routines also have limited support for this long string convention,

52 CHAPTER 5. CFITSIO CONVENTIONS AND GUIDELINES
fits—modify—key—str ­ modify an existing string keyword value
fits—update—key—str ­ update a string keyword value
in that they will correctly overwrite an existing long string value, but the new string value is limited
to a maximum of 68 characters in length.
The more commonly used CFITSIO routines to write string valued keywords (fits update key and
fits write key) do not support this long string convention and only support strings up to 68 char­
acters in length. This has been done deliberately to prevent programs from inadvertently writing
keywords using this non­standard convention without the explicit intent of the programmer or user.
The fits write key longstr routine must be called instead to write long strings. This routine can
also be used to write ordinary string values less than 68 characters in length.
5.14.2 Arrays of Fixed­Length Strings in Binary Tables
The definition of the FITS binary table extension format does not provide a simple way to specify
that a character column contains an array of fixed­length strings. To support this feature, CFITSIO
uses a local convention for the format of the TFORMn keyword value of the form 'rAw' where 'r'
is an integer specifying the total width in characters of the column, and 'w' is an integer specifying
the (fixed) length of an individual unit string within the vector. For example, TFORM1 = '120A10'
would indicate that the binary table column is 120 characters wide and consists of 12 10­character
length strings. This convention is recognized by the CFITSIO routines that read or write strings in
binary tables. The Binary Table definition document specifies that other optional characters may
follow the datatype code in the TFORM keyword, so this local convention is in compliance with
the FITS standard although other FITS readers may not recognize this convention.
The Binary Table definition document that was approved by the IAU in 1994 contains an appendix
describing an alternate convention for specifying arrays of fixed or variable length strings in a binary
table character column (with the form 'rA:SSTRw/nnn)'. This appendix was not officially voted
on by the IAU and hence is still provisional. CFITSIO does not currently support this proposal.
5.14.3 Keyword Units Strings
One deficiency of the current FITS Standard is that it does not define a specific convention for
recording the physical units of a keyword value. The TUNITn keyword can be used to specify the
physical units of the values in a table column, but there is no comparable convention for keyword
values. The comment field of the keyword is often used for this purpose, but the units are usually
not specified in a well defined format that FITS readers can easily recognize and extract.
To solve this deficiency, CFITSIO uses a local convention in which the keyword units are enclosed in
square brackets as the first token in the keyword comment field; more specifically, the opening square
bracket immediately follows the slash '/' comment field delimiter and a single space character. The
following examples illustrate keywords that use this convention:
EXPOSURE= 1800.0 / [s] elapsed exposure time

5.14. LOCAL FITS CONVENTIONS SUPPORTED BY CFITSIO 53
V—HELIO = 16.23 / [km s**(­1)] heliocentric velocity
LAMBDA = 5400. / [angstrom] central wavelength
FLUX = 4.9033487787637465E­30 / [J/cm**2/s] average flux
In general, the units named in the IAU(1988) Style Guide are recommended, with the main excep­
tion that the preferred unit for angle is 'deg' for degrees.
The fits read key unit and fits write key unit routines in CFITSIO read and write, respectively,
the keyword unit strings in an existing keyword.
5.14.4 HIERARCH Convention for Extended Keyword Names
CFITSIO supports the HIERARCH keyword convention which allows keyword names that are
longer then 8 characters and may contain the full range of printable ASCII text characters. This
convention was developed at the European Southern Observatory (ESO) to support hierarchical
FITS keyword such as:
HIERARCH ESO INS FOCU POS = ­0.00002500 / Focus position
Basically, this convention uses the FITS keyword 'HIERARCH' to indicate that this conven­
tion is being used, then the actual keyword name ('ESO INS FOCU POS' in this example) be­
gins in column 10 and can contain any printable ASCII text characters, including spaces. The
equals sign marks the end of the keyword name and is followed by the usual value and com­
ment fields just as in standard FITS keywords. Further details of this convention are described at
http://arcdev.hq.eso.org/dicb/dicd/dic­1­1.4.html (search for HIERARCH).
This convention allows a much broader range of keyword names than is allowed by the FITS
Standard. Here are more examples of such keywords:
HIERARCH LongKeyword = 47.5 / Keyword has ? 8 characters, and mixed case
HIERARCH XTE$TEMP = 98.6 / Keyword contains the '$' character
HIERARCH Earth is a star = F / Keyword contains embedded spaces
CFITSIO will transparently read and write these keywords, so application programs do not in
general need to know anything about the specific implementation details of the HIERARCH con­
vention. In particular, application programs do not need to specify the `HIERARCH' part of the
keyword name when reading or writing keywords (although it may be included if desired). When
writing a keyword, CFITSIO first checks to see if the keyword name is legal as a standard FITS
keyword (no more than 8 characters long and containing only letters, digits, or a minus sign or
underscore). If so it writes it as a standard FITS keyword, otherwise it uses the hierarch con­
vention to write the keyword. The maximum keyword name length is 67 characters, which leaves
only 1 space for the value field. A more practical limit is about 40 characters, which leaves enough
room for most keyword values. CFITSIO returns an error if there is not enough room for both the
keyword name and the keyword value on the 80­character card, except for string­valued keywords
which are simply truncated so that the closing quote character falls in column 80. In the current

54 CHAPTER 5. CFITSIO CONVENTIONS AND GUIDELINES
implementation, CFITSIO preserves the case of the letters when writing the keyword name, but it
is case­insensitive when reading or searching for a keyword. The current implementation allows any
ASCII text character (ASCII 32 to ASCII 126) in the keyword name except for the '=' character.
A space is also required on either side of the equal sign.
5.15 Optimizing Code for Maximum Processing Speed
CFITSIO has been carefully designed to obtain the highest possible speed when reading and writing
FITS files. In order to achieve the best performance, however, application programmers must be
careful to call the CFITSIO routines appropriately and in an efficient sequence; inappropriate usage
of CFITSIO routines can greatly slow down the execution speed of a program.
The maximum possible I/O speed of CFITSIO depends of course on the type of computer system
that it is running on. As a rough guide, the current generation of workstations can achieve speeds
of 2 -- 10 MB/s when reading or writing FITS images and similar, or slightly slower speeds with
FITS binary tables. Reading of FITS files can occur at even higher rates (30MB/s or more) if the
FITS file is still cached in system memory following a previous read or write operation on the same
file. To more accurately predict the best performance that is possible on any particular system, a
diagnostic program called ``speed.c'' is included with the CFITSIO distribution which can be run
to approximately measure the maximum possible speed of writing and reading a test FITS file.
The following 2 sections provide some background on how CFITSIO internally manages the data
I/O and describes some strategies that may be used to optimize the processing speed of software
that uses CFITSIO.
5.15.1 Background Information: How CFITSIO Manages Data I/O
Many CFITSIO operations involve transferring only a small number of bytes to or from the FITS file
(e.g, reading a keyword, or writing a row in a table); it would be very inefficient to physically read
or write such small blocks of data directly in the FITS file on disk, therefore CFITSIO maintains
a set of internal Input--Output (IO) buffers in RAM memory that each contain one FITS block
(2880 bytes) of data. Whenever CFITSIO needs to access data in the FITS file, it first transfers the
FITS block containing those bytes into one of the IO buffers in memory. The next time CFITSIO
needs to access bytes in the same block it can then go to the fast IO buffer rather than using a
much slower system disk access routine. The number of available IO buffers is determined by the
NIOBUF parameter (in fitsio2.h) and is currently set to 25.
Whenever CFITSIO reads or writes data it first checks to see if that block of the FITS file is already
loaded into one of the IO buffers. If not, and if there is an empty IO buffer available, then it will
load that block into the IO buffer (when reading a FITS file) or will initialize a new block (when
writing to a FITS file). If all the IO buffers are already full, it must decide which one to reuse
(generally the one that has been accessed least recently), and flush the contents back to disk if it
has been modified before loading the new block.
The one major exception to the above process occurs whenever a large contiguous set of bytes are
accessed, as might occur when reading or writing a FITS image. In this case CFITSIO bypasses

5.15. OPTIMIZING CODE FOR MAXIMUM PROCESSING SPEED 55
the internal IO buffers and simply reads or writes the desired bytes directly in the disk file with
a single call to a low­level file read or write routine. The minimum threshold for the number of
bytes to read or write this way is set by the MINDIRECT parameter and is currently set to 3
FITS blocks = 8640 bytes. This is the most efficient way to read or write large chunks of data and
can achieve IO transfer rates of 5 -- 10MB/s or greater. Note that this fast direct IO process is
not applicable when accessing columns of data in a FITS table because the bytes are generally not
contiguous since they are interleaved by the other columns of data in the table. This explains why
the speed for accessing FITS tables is generally slower than accessing FITS images.
Given this background information, the general strategy for efficiently accessing FITS files should
now be apparent: when dealing with FITS images, read or write large chunks of data at a time
so that the direct IO mechanism will be invoked; when accessing FITS headers or FITS tables, on
the other hand, once a particular FITS block has been loading into one of the IO buffers, try to
access all the needed information in that block before it gets flushed out of the IO buffer. It is
important to avoid the situation where the same FITS block is being read then flushed from a IO
buffer multiple times.
The following section gives more specific suggestions for optimizing the use of CFITSIO.
5.15.2 Optimization Strategies
1. When dealing with a FITS primary array or IMAGE extension, it is more efficient to read or
write large chunks of the image at a time (at least 3 FITS blocks = 8640 bytes) so that the direct
IO mechanism will be used as described in the previous section. Smaller chunks of data are read
or written via the IO buffers, which is somewhat less efficient because of the extra copy operation
and additional bookkeeping steps that are required. In principle it is more efficient to read or write
as big an array of image pixels at one time as possible, however, if the array becomes so large that
the operating system cannot store it all in RAM, then the performance may be degraded because
of the increased swapping of virtual memory to disk.
2. When dealing with FITS tables, the most important efficiency factor in the software design is
to read or write the data in the FITS file in a single pass through the file. An example of poor
program design would be to read a large, 3­column table by sequentially reading the entire first
column, then going back to read the 2nd column, and finally the 3rd column; this obviously requires
3 passes through the file which could triple the execution time of an IO limited program. For small
tables this is not important, but when reading multi­megabyte sized tables these inefficiencies can
become significant. The more efficient procedure in this case is to read or write only as many rows
of the table as will fit into the available internal IO buffers, then access all the necessary columns
of data within that range of rows. Then after the program is completely finished with the data in
those rows it can move on to the next range of rows that will fit in the buffers, continuing in this
way until the entire file has been processed. By using this procedure of accessing all the columns of
a table in parallel rather than sequentially, each block of the FITS file will only be read or written
once.
The optimal number of rows to read or write at one time in a given table depends on the width of
the table row, on the number of IO buffers that have been allocated in CFITSIO, and also on the
number of other FITS files that are open at the same time (since one IO buffer is always reserved

56 CHAPTER 5. CFITSIO CONVENTIONS AND GUIDELINES
for each open FITS file). Fortunately, a CFITSIO routine is available that will return the optimal
number of rows for a given table: fits get rowsize. It is not critical to use exactly the value of nrows
returned by this routine, as long as one does not exceed it. Using a very small value however can
also lead to poor performance because of the overhead from the larger number of subroutine calls.
The optimal number of rows returned by fits get rowsize is valid only as long as the application
program is only reading or writing data in the specified table. Any other calls to access data in the
table header or in any other FITS file would cause additional blocks of data to be loaded into the
IO buffers displacing data from the original table, and should be avoided during the critical period
while the table is being read or written.
Occasionally it is necessary to simultaneously access more than one FITS table, for example when
transferring values from an input table to an output table. In cases like this, one should call
fits get rowsize to get the optimal number of rows for each table separately, than reduce the number
of rows proportionally. For example, if the optimal number of rows in the input table is 3600 and
is 1400 in the output table, then these values should be cut in half to 1800 and 700, respectively,
if both tables are going to be accessed at the same time.
3. Alway use binary table extensions rather than ASCII table extensions for better efficiency when
dealing with tabular data. The I/O to ASCII tables is slower because of the overhead in formatting
or parsing the ASCII data fields and because ASCII tables are about twice as large as binary tables
with the same information content.
4. Design software so that it reads the FITS header keywords in the same order in which they
occur in the file. When reading keywords, CFITSIO searches forward starting from the position of
the last keyword that was read. If it reaches the end of the header without finding the keyword, it
then goes back to the start of the header and continues the search down to the position where it
started. In practice, as long as the entire FITS header can fit at one time in the available internal
IO buffers, then the header keyword access will be very fast and it makes little difference which
order they are accessed.
5. Avoid the use of scaling (by using the BSCALE and BZERO or TSCAL and TZERO keywords)
in FITS files since the scaling operations add to the processing time needed to read or write the
data. In some cases it may be more efficient to temporarily turn off the scaling (using fits set bscale
or fits set tscale) and then read or write the raw unscaled values in the FITS file.
6. Avoid using the `implicit datatype conversion' capability in CFITSIO. For instance, when
reading a FITS image with BITPIX = ­32 (32­bit floating point pixels), read the data into a single
precision floating point data array in the program. Forcing CFITSIO to convert the data to a
different datatype can slow the program.
7. Where feasible, design FITS binary tables using vector column elements so that the data are
written as a contiguous set of bytes, rather than as single elements in multiple rows. For example,
it is faster to access the data in a table that contains a single row and 2 columns with TFORM
keywords equal to '10000E' and '10000J', than it is to access the same amount of data in a table
with 10000 rows which has columns with the TFORM keywords equal to '1E' and '1J'. In the
former case the 10000 floating point values in the first column are all written in a contiguous block
of the file which can be read or written quickly, whereas in the second case each floating point value
in the first column is interleaved with the integer value in the second column of the same row so

5.15. OPTIMIZING CODE FOR MAXIMUM PROCESSING SPEED 57
CFITSIO has to explicitly move to the position of each element to be read or written.
8. Avoid the use of variable length vector columns in binary tables, since any reading or writing
of these data requires that CFITSIO first look up or compute the starting address of each row of
data in the heap.
9. When copying data from one FITS table to another, it is faster to transfer the raw bytes
instead of reading then writing each column of the table. The CFITSIO routines fits read tblbytes
and fits write tblbytes will perform low­level reads or writes of any contiguous range of bytes in
a table extension. These routines can be used to read or write a whole row (or multiple rows for
even greater efficiency) of a table with a single function call. These routines are fast because they
bypass all the usual data scaling, error checking and machine dependent data conversion that is
normally done by CFITSIO, and they allow the program to write the data to the output file in
exactly the same byte order. For these same reasons, these routines can corrupt the FITS data file
if used incorrectly because no validation or machine dependent conversion is performed by these
routines. These routines are only recommended for optimizing critical pieces of code and should
only be used by programmers who thoroughly understand the internal format of the FITS tables
they are reading or writing.
10. Another strategy for improving the speed of writing a FITS table, similar to the previous one,
is to directly construct the entire byte stream for a whole table row (or multiple rows) within the
application program and then write it to the FITS file with fits write tblbytes. This avoids all the
overhead normally present in the column­oriented CFITSIO write routines. This technique should
only be used for critical applications, because it makes the code more difficult to understand and
maintain, and it makes the code more system dependent (e.g., do the bytes need to be swapped
before writing to the FITS file?).
11. Finally, external factors such as the type of magnetic disk controller (SCSI or IDE), the size
of the disk cache, the average seek speed of the disk, the amount of disk fragmentation, and the
amount of RAM available on the system can all have a significant impact on overall I/O efficiency.
For critical applications, a system administrator should review the proposed system hardware to
identify any potential I/O bottlenecks.

58 CHAPTER 5. CFITSIO CONVENTIONS AND GUIDELINES

Chapter 6
The CFITSIO Iterator Function
The fits iterate data function in CFITSIO provides a unique method of executing an arbitrary
user­supplied `work' function that operates on rows of data in FITS tables or on pixels in FITS
images. Rather than explicitly reading and writing the FITS images or columns of data, one instead
calls the CFITSIO iterator routine, passing to it the name of the user's work function that is to
be executed along with a list of all the table columns or image arrays that are to be passed to the
work function. The CFITSIO iterator function then does all the work of allocating memory for
the arrays, reading the input data from the FITS file, passing them to the work function, and then
writing any output data back to the FITS file after the work function exits. Because it is often
more efficient to process only a subset of the total table rows at one time, the iterator function
can determine the optimum amount of data to pass in each iteration and repeatly call the work
function until the entire table been processed.
For many applications this single CFITSIO iterator function can effectively replace all the other
CFITSIO routines for reading or writing data in FITS images or tables. Using the iterator has
several important advantages over the traditional method of reading and writing FITS data files:
ffl It cleanly separates the data I/O from the routine that operates on the data. This leads to
a more modular and `object oriented' programming style.
ffl It simplifies the application program by eliminating the need to allocate memory for the data
arrays and eliminates most of the calls to the CFITSIO routines that explicitly read and write
the data.
ffl It ensures that the data are processed as efficiently as possible. This is especially important
when processing tabular data since the iterator function will calculate the most efficient
number of rows in the table to be passed at one time to the user's work function on each
iteration.
ffl Makes it possible for larger projects to develop a library of work functions that all have a
uniform calling sequence and are all independent of the details of the FITS file format.
There are basically 2 steps in using the CFITSIO iterator function. The first step is to design the
work function itself which must have a prescribed set of input parameters. One of these parameters
59

60 CHAPTER 6. THE CFITSIO ITERATOR FUNCTION
is a structure containing pointers to the arrays of data; the work function can perform any desired
operations on these arrays and does not need to worry about how the input data were read from
the file or how the output data get written back to the file.
The second step is to design the driver routine that opens all the necessary FITS files and initializes
the input parameters to the iterator function. The driver program calls the CFITSIO iterator
function which then reads the data and passes it to the user's work function.
The following 2 sections describe these steps in more detail. There are also several example programs
included with the CFITSIO distribution which illustrate how to use the iterator function.
6.1 The Iterator Work Function
The user­supplied iterator work function must have the following set of input parameters (the
function can be given any desired name):
int user—fn( long totaln, long offset, long firstn, long nvalues,
int narrays, iteratorCol *data, void *userPointer )
ffl totaln -- the total number of table rows or image pixels that will be passed to the work function
during 1 or more iterations.
ffl offset -- the offset applied to the first table row or image pixel to be passed to the work
function. In other words, this is the number of rows or pixels that are skipped over before
starting the iterations. If offset = 0, then all the table rows or image pixels will be passed to
the work function.
ffl firstn -- the number of the first table row or image pixel (starting with 1) that is being passed
in this particular call to the work function.
ffl nvalues -- the number of table rows or image pixels that are being passed in this particular
call to the work function. nvalues will always be less than or equal to totaln and will have
the same value on each iteration, except possibly on the last call which may have a smaller
value.
ffl narrays -- the number of arrays of data that are being passed to the work function. There is
one array for each image or table column.
ffl *data -- array of structures, one for each column or image. Each structure contains a pointer
to the array of data as well as other descriptive parameters about that array.
ffl *userPointer -- a user supplied pointer that can be used to pass ancillary information from the
driver function to the work function. This pointer is passed to the CFITSIO iterator function
which then passes it on to the work function without any modification. It may point to a
single number, to an array of values, to a structure containing an arbitrary set of parameters
of different types, or it may be a null pointer if it is not needed. The work function must cast
this pointer to the appropriate data type before using it it.

6.1. THE ITERATOR WORK FUNCTION 61
The totaln, offset, narrays, data, and userPointer parameters are guaranteed to have the same value
on each iteration. Only firstn, nvalues, and the arrays of data pointed to by the data structures
may change on each iterative call to the work function.
Note that the iterator treats an image as a long 1­D array of pixels regardless of it's intrinsic
dimensionality. The total number of pixels is just the product of the size of each dimension, and
the order of the pixels is the same as the order that they are stored in the FITS file. If the work
function needs to know the number and size of the image dimensions then these parameters can be
passed via the userPointer structure.
The iteratorCol structure is currently defined as follows:
typedef struct /* structure for the iterator function column information */
--
/* structure elements required as input to fits—iterate—data: */
fitsfile *fptr; /* pointer to the HDU containing the column or image */
int colnum; /* column number in the table; ignored for images */
char colname[70]; /* name (TTYPEn) of the column; null for images */
int datatype; /* output datatype (converted if necessary) */
int iotype; /* type: InputCol, InputOutputCol, or OutputCol */
/* output structure elements that may be useful for the work function: */
void *array; /* pointer to the array (and the null value) */
long repeat; /* binary table vector repeat value; set */
/* equal to 1 for images */
long tlmin; /* legal minimum data value, if any */
long tlmax; /* legal maximum data value, if any */
char unit[70]; /* physical unit string (BUNIT or TUNITn) */
char tdisp[70]; /* suggested display format; null if none */
ť iteratorCol;
Instead of directly reading or writing the elements in this structure, it is recommended that pro­
grammers use the access functions that are provided for this purpose.
The first five elements in this structure must be initially defined by the driver routine before calling
the iterator routine. The CFITSIO iterator routine uses this information to determine what column
or array to pass to the work function, and whether the array is to be input to the work function,
output from the work function, or both. The CFITSIO iterator function fills in the values of the
remaining structure elements before passing it to the work function.
The array structure element is a pointer to the actual data array and it must be cast to the correct
data type before it is used. The `repeat' structure element give the number of data values in
each row of the table, so that the total number of data values in the array is given by repeat *
nvalues. In the case of image arrays and ASCII tables, repeat will always be equal to 1. When the

62 CHAPTER 6. THE CFITSIO ITERATOR FUNCTION
datatype is a character string, the array pointer is actually a pointer to an array of string pointers
(i.e., char **array). The other output structure elements are provided for convenience in case that
information is needed within the work function. Any other information may be passed from the
driver routine to the work function via the userPointer parameter.
Upon completion, the work routine must return an integer status value, with 0 indicating success
and any other value indicating an error which will cause the iterator function to immediately exit
at that point. Return status values in the range 1 -- 1000 should be avoided since these are reserved
for use by CFITSIO. A return status value of ­1 may be used to force the CFITSIO iterator function
to stop at that point and return control to the driver routine after writing any output arrays to the
FITS file. CFITSIO does not considered this to be an error condition, so any further processing by
the application program will continue normally.
6.2 The Iterator Driver Function
The iterator driver function must open the necessary FITS files and position them to the correct
HDU. It must also initialize the following parameters in the iteratorCol structure (defined above) for
each column or image before calling the CFITSIO iterator function. Several `constructor' routines
are provided in CFITSIO for this purpose.
ffl *fptr -- The fitsfile pointer to the table or image.
ffl colnum -- the number of the column in the table. This value is ignored in the case of images.
If colnum equals 0, then the column name will be used to identify the column to be passed
to the work function.
ffl colname -- the name (TTYPEn keyword) of the column. This is only required if colnum = 0
and is ignored for images.
ffl datatype -- The desired datatype of the array to be passed to the work function. For numerical
data the datatype does not need to be the same as the actual datatype in the FITS file, in
which case CFITSIO will do the conversion. Allowed values are: TSTRING, TLOGICAL,
TBYTE, TSHORT, TUSHORT, TINT, TLONG, TULONG, TFLOAT, TDOUBLE. If the
input value of datatype equals 0, then the existing datatype of the column or image will be
used without any conversion.
ffl iotype -- defines whether the data array is to be input to the work function (i.e, read from the
FITS file), or output from the work function (i.e., written to the FITS file) or both. Allowed
values are InputCol, OutputCol, or InputOutputCol.
After the driver routine has initialized all these parameters, it can then call the CFITSIO iterator
function:
int fits—iterate—data(int narrays, iteratorCol *data, long offset,
long nPerLoop, int (*workFn)( ), void *userPointer, int *status);

6.3. GUIDELINES FOR USING THE ITERATOR FUNCTION 63
ffl narrays -- the number of columns or images that are to be passed to the work function.
ffl *data -- pointer to array of structures containing information about each column or image.
ffl offset -- if positive, this number of rows at the beginning of the table (or pixels in the image)
will be skipped and will not be passed to the work function.
ffl nPerLoop ­ specifies the number of table rows (or number of image pixels) that are to be
passed to the work function on each iteration. If nPerLoop = 0 then CFITSIO will calculate
the optimum number for greatest efficiency. If nPerLoop is negative, then all the rows or
pixels will be passed at one time, and the work function will only be called once.
ffl *workFn ­ the name (actually the address) of the work function that is to be called by
fits iterate data.
ffl *userPointer ­ this is a user supplied pointer that can be used to pass ancillary information
from the driver routine to the work function. It may point to a single number, an array, or
to a structure containing an arbitrary set of parameters.
ffl *status ­ The CFITSIO error status. Should = 0 on input; a non­zero output value indicates
an error.
When fits iterate data is called it first allocates memory to hold all the requested columns of data
or image pixel arrays. It then reads the input data from the FITS tables or images into the arrays
then passes the structure with pointers to these data arrays to the work function. After the work
function returns, the iterator function writes any output columns of data or images back to the
FITS files. It then repeats this process for any remaining sets of rows or image pixels until it has
processed the entire table or image or until the work function returns a non­zero status value. The
iterator then frees the memory that it initially allocated and returns control to the driver routine
that called it.
6.3 Guidelines for Using the Iterator Function
The totaln, offset, firstn, and nvalues parameters that are passed to the work function are useful
for determining how much of the data has been processed and how much remains left to do. On
the very first call to the work function firstn will be equal to offset + 1; the work function may
need to perform various initialization tasks before starting to process the data. Similarly, firstn +
nvalues ­ 1 will be equal to totaln on the last iteration, at which point the work function may need
to perform some clean up operations before exiting for the last time. The work function can also
force an early termination of the iterations by returning a status value = ­1.
The narrays and iteratorCol.datatype arguments allow the work function to double check that the
number of input arrays and their datatypes have the expected values. The iteratorCol.fptr and
iteratorCol.colnum structure elements can be used if the work function needs to read or write the
values of other keywords in the FITS file associated with the array. This should generally only be
done during the initialization step or during the clean up step after the last set of data has been

64 CHAPTER 6. THE CFITSIO ITERATOR FUNCTION
processed. Extra FITS file I/O during the main processing loop of the work function can seriously
degrade the speed of the program.
One important feature of the iterator is that the first element in each array that is passed to the
work function gives the value that is used to represent null or undefined values in the array. The
real data then begins with the second element of the array (i.e., array[1], not array[0]). If the first
array element is equal to zero, then this indicates that all the array elements have defined values and
there are no undefined values. If array[0] is not equal to zero, then this indicates that some of the
data values are undefined and this value (array[0]) is used to represent them. In the case of output
arrays (i.e., those arrays that will be written back to the FITS file by the iterator function after the
work function exits) the work function must set the first array element to the desired null value if
necessary, otherwise the first element should be set to zero to indicate that there are no null values
in the output array. CFITSIO defines 2 values, FLOATNULLVALUE and DOUBLENULLVALUE,
that can be used as default null values for float and double datatypes, respectively. In the case of
character string datatypes, a null string is always used to represent undefined strings.
In some applications it may be necessary to recursively call the iterator function. An example of
this is given by one of the example programs that is distributed with CFITSIO: it first calls a work
function that writes out a 2D histogram image. That work function in turn calls another work
function that reads the `X' and `Y' columns in a table to calculate the value of each 2D histogram
image pixel. Graphically, the program structure can be described as:
driver ­­? iterator ­­? work1—fn ­­? iterator ­­? work2—fn
Finally, it should be noted that the table columns or image arrays that are passed to the work
function do not all have to come from the same FITS file and instead may come from any com­
bination of sources as long as they have the same length. The length of the first table column or
image array is used by the iterator if they do not all have the same length.

Chapter 7
Basic CFITSIO Interface Routines
This chapter describes the basic routines in the CFITSIO user interface that provide all the func­
tions normally needed to read and write most FITS files. It is recommended that these routines
be used for most applications and that the more advanced routines described in the next chapter
only be used in special circumstances when necessary.
The following conventions are used in this chapter in the description of each function:
1. Most functions have 2 names: a long descriptive name and a short concise name. Both names are
listed on the first line of the following descriptions, separated by a slash (/) character. Programmers
may use either name in their programs but the long names are recommended to help document the
code and make it easier to read.
2. A right arrow symbol (?) is used in the function descriptions to separate the input parameters
from the output parameters in the definition of each routine. This symbol is not actually part of
the C calling sequence.
3. The function parameters are defined in more detail in the alphabetical listing in the appendix.
4. The first argument in almost all the functions is a pointer to a structure of type `fitsfile'. Memory
for this structure is allocated by CFITSIO when the FITS file is first opened or created and is freed
when the FITS file is closed.
5. The last argument in almost all the functions is the error status parameter. It must be equal
to 0 on input, otherwise the function will immediately exit without doing anything. A non­zero
output value indicates that an error occurred in the function. In most cases the status value is also
returned as the value of the function itself.
7.1 CFITSIO Error Status Routines
1 Return the revision number of the CFITSIO library. The revision number will be incremented
whenever any modifications or enhancements are made to the code.
float fits—get—version / ffvers ( ? float *version)
65

66 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
2 Return a descriptive text string (30 char max.) corresponding to a CFITSIO error status code.
void fits—get—errstatus / ffgerr (int status, ? char *err—text)
3 Return the top (oldest) 80­character error message from the internal CFITSIO stack of error
messages and shift any remaining messages on the stack up one level. Call this routine
repeatedly to get each message in sequence. The function returns a value = 0 and a null error
message when the error stack is empty.
int fits—read—errmsg / ffgmsg (char *err—msg)
4 Print out the error message corresponding to the input status value and all the error messages
on the CFITSIO stack to the specified file stream (normally to stdout or stderr). If the input
status value = 0 then this routine does nothing.
void fits—report—error / ffrprt (FILE *stream, ? status)
5 Write an 80­character message to the CFITSIO error stack. Application programs should not
normally write to the stack, but there may be some situations where this is desirable.
void fits—write—errmsg / ffpmsg (char *err—msg)
6 Clear the entire error message stack. This routine is useful to clear any error message that
may have been generated by a non­fatal CFITSIO error. This routine is called without any
arguments.
void fits—clear—errmsg / ffcmsg (void)
7.2 FITS File Access Routines
These routines will open or close a new or existing FITS file or return information about the opened
FITS file. These routines support the extended file name syntax that is described in a previous
chapter.
The same FITS file may be opened more than once simultaneously and the resulting pointers to
the files may be treated as though they were completely independent FITS files. Thus, one could
open a FITS file twice, move to different extensions within the file, and then read or write data to
the 2 extensions in any order.
1 Open an existing FITS file with a specified access mode. The iomode parameter may have a
value of READONLY or READWRITE.

7.2. FITS FILE ACCESS ROUTINES 67
int fits—open—file / ffopen
(fitsfile **fptr, char *filename, int iomode, ? int *status)
2 Reopen a FITS file that was previously opened with fits open file or fits create file. The new
fitsfile pointer may then be treated as a separate file, and one may simultaneously read or
write to 2 (or more) different extensions in the same file. The fits open file routine (above)
automatically detects cases where a previously opened file is being opened again, and then
internally call fits reopen file, so programs should rarely need to explicitly call this routine.
int fits—reopen—file / ffreopen
(fitsfile *openfptr, fitsfile **newfptr, ? int *status)
3 Create a new empty FITS file. An error will be returned if the specified file already exists unless
the filename is prefixed with an exclamation point (!). In that case CFITSIO will overwrite
the existing file. Note that the exclamation point, ' !', is a special UNIX character, so if it is
used on the command line rather than entered at a task prompt, it must be preceded by a
backslash to force the UNIX shell to ignore it.
int fits—create—file / ffinit
(fitsfile **fptr, char *filename, ? int *status)
4 Create a new FITS file, using a template file to define its initial size and structure. The template
may be another FITS HDU or an ASCII template file. If the input template file name pointer
is null, then this routine behaves the same as fits create file. The currently supported format
of the ASCII template file is described under the fits parse template routine (in the general
Utilities section), but this may change slightly in later releases of CFITSIO.
int fits—create—template / fftplt
(fitsfile **fptr, char *filename, char *tpltfile ? int *status)
5 Close a previously opened FITS file.
int fits—close—file / ffclos (fitsfile *fptr, ? int *status)
6 Close and DELETE a FITS disk file previously opened with ffopen or ffinit. This routine may
be useful in cases where a FITS file is created but then an error occurs which prevents the
file from being completed.
int fits—delete—file / ffdelt
(fitsfile *fptr, ? int *status)
7 Return the name of the opened FITS file.

68 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
int fits—file—name / ffflnm
(fitsfile *fptr, ? char *filename, int *status)
8 Return the I/O mode of the open FITS file (READONLY or READWRITE).
int fits—file—mode / ffflmd
(fitsfile *fptr, ? int *iomode, int *status)
9 Return the file type of the opened FITS file (e.g. 'file://', 'ftp://', etc.).
int fits—url—type / ffurlt
(fitsfile *fptr, ? char *urltype, int *status)
10 Parse the input filename or URL into its component parts: the file type (file://, ftp://, http://,
etc), the base input file name, the name of the output file that the input file is to be copied
to prior to opening, the HDU or extension specification, the filtering specifier, the binning
specifier, and the column specifier. Null strings will be returned for any components that are
not present in the input file name.
int fits—parse—input—url / ffiurl
(char *filename, ? char *filetype, char *infile, char *outfile, char
*extspec, char *filter, char *binspec, char *colspec, int *status)
11 Parse the input filename and return the HDU number that would be moved to if the file were
opened with fits open file. The returned HDU number begins with 1 for the primary array,
so for example, if the input filename = `myfile.fits[2]' then hdunum = 3 will be returned. If
an extension name is included in the file name specification (e.g. `myfile.fits[EVENTS]' then
this routine will have to open the FITS file and look for the position of the named extension,
then close file. This is not possible if the file is being read from the stdin stream, and an
error will be returned in this case. If the filename does not specify an explicit extension (e.g.
'myfile.fits') then hdunum = ­99 will be returned, which is functionally equivalent to hdunum
= 1. This routine is mainly used for backward compatibility in the ftools software package
and is not recommended for general use. It is generally better and more efficient to first open
the FITS file with fits open file, then use fits get hdu num to determine which HDU in the
file has been opened, rather than calling fits parse input url then calling fits open file.
int fits—parse—extnum / ffextn
(char *filename, ? int *hdunum, int *status)
12 Parse the input file name and return the root file name. The root name includes the file
type if specified, (e.g. 'ftp://' or 'http://') and the full path name, to the extent that it is
specified in the input filename. It does not enclude the HDU name or number, or any filtering
specifications.
int fits—parse—rootname / ffrtnm
(char *filename, ? char *rootname, int *status);

7.3. HDU ACCESS ROUTINES 69
7.3 HDU Access Routines
The following functions perform operations on Header­Data Units (HDUs) as a whole.
1 Move to a specified absolute HDU number in the FITS file. When a FITS file is first opened or
created it is automatically positioned to the first HDU (the primary array) in the file which
has hdunum = 1. A null pointer may be given for the hdutype parameter if it's value is not
needed.
int fits—movabs—hdu / ffmahd
(fitsfile *fptr, int hdunum, ? int *hdutype, int *status)
2 Move a relative number of HDUs forward or backwards in the FITS file from the current position.
A null pointer may be given for the hdutype parameter if it's value is not needed.
int fits—movrel—hdu / ffmrhd
(fitsfile *fptr, int nmove, ? int *hdutype, int *status)
3 Move to the (first) HDU which has the specified extension type and EXTNAME (or HDUNAME)
and EXTVERS keyword values. The hdutype parameter may have a value of IMAGE HDU,
ASCII TBL, BINARY TBL, or ANY HDU where ANY HDU means that only the extname
and extvers values will be used to locate the correct extension. If the input value of extvers
is 0 then the EXTVERS keyword is ignored and the first HDU with a matching EXTNAME
(or HDUNAME) keyword will be found. If no matching HDU is found in the file then the
current HDU will remain unchanged and a status = BAD HDU NUM will be returned.
int fits—movnam—hdu / ffmnhd
(fitsfile *fptr, int hdutype, char *extname, int extvers, ? int *status)
4 Return the number of the current HDU in the FITS file (primary array = 1). This function
returns the HDU number rather than a status value.
int fits—get—hdu—num / ffghdn
(fitsfile *fptr, ? int *hdunum)
5 Return the type of the current HDU in the FITS file. The possible values for hdutype are:
IMAGE HDU, ASCII TBL, or BINARY TBL.
int fits—get—hdu—type / ffghdt
(fitsfile *fptr, ? int *hdutype, int *status)
6 Return the total number of HDUs in the FITS file. The CHDU remains unchanged.

70 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
int fits—get—num—hdus / ffthdu
(fitsfile *fptr, ? int *hdunum, int *status)
7 Create a new primary array or IMAGE extension. If the FITS file is currently empty then a
primary array is created, otherwise a new IMAGE extension is appended to the file.
int fits—create—img / ffcrim
( fitsfile *fptr, int bitpix, int naxis, long *naxes, ? int *status)
8 Create a new ASCII or bintable table extension. If the FITS file is currently empty then a
dummy primary array will be created before appending the table extension to it. The tbltype
parameter defines the type of table and can have values of ASCII TBL or BINARY TBL.
The naxis2 parameter gives the initial number of rows to be created in the table, and should
normally be set = 0. CFITSIO will automatically increase the size of the table as additional
rows are written. A non­zero number of rows may be specified to reserve space for that many
rows, even if a fewer number of rows will be written. The tunit and extname parameters
are optional and a null pointer may be given if they are not defined. The FITS Standard
recommends that only letters, digits, and the underscore character be used in column names
(the ttype parameter) with no embedded spaces). Trailing blank characters are not significant.
It is recommended that all the column names in a given table be unique within the first 8
characters, and strongly recommended that the names be unique within the first 16 characters.
int fits—create—tbl / ffcrtb
(fitsfile *fptr, int tbltype, long naxis2, int tfields, char *ttype[],
char *tform[], char *tunit[], char *extname, int *status)
9 Copy the CHDU from the FITS file associated with infptr and append it to the end of the FITS
file associated with outfptr. Space may be reserved for MOREKEYS additional keywords in
the output header.
int fits—copy—hdu / ffcopy
(fitsfile *infptr, fitsfile *outfptr, int morekeys, ? int *status)
10 Delete the CHDU in the FITS file. Any following HDUs will be shifted forward in the file, to fill
in the gap created by the deleted HDU. This routine will only delete extensions; the primary
array (the first HDU in the file) cannot be deleted. The physical size of the FITS file will
not necessarily be reduced. If there are more extensions in the file following the one that is
deleted, then the the CHDU will be redefined to point to the following extension. If there are
no following extensions then the CHDU will be redefined to point to the previous HDU. The
output hdutype parameter returns the type of the new CHDU. A null pointer may be given
for hdutype if the returned value is not needed.
int fits—delete—hdu / ffdhdu
(fitsfile *fptr, ? int *hdutype, int *status)

7.4. HEADER KEYWORD READ/WRITE ROUTINES 71
7.4 Header Keyword Read/Write Routines
These routines read or write keywords in the Current Header Unit (CHU). Wild card characters
(*, ?, or #) may be used when specifying the name of the keyword to be read: a ' ?' will match any
single character at that position in the keyword name and a '*' will match any length (including
zero) string of characters. The '#' character will match any consecutive string of decimal digits (0
­ 9). When a wild card is used the routine will only search for a match from the current header
position to the end of the header and will not resume the search from the top of the header back to
the original header position as is done when no wildcards are included in the keyword name. The
fits read record routine may be used to set the starting position when doing wild card searchs. A
status value of KEY NO EXIST is returned if the specified keyword to be read is not found in the
header.
1 Return the number of existing keywords (not counting the END keyword) and the amount of
space currently available for more keywords. It returns morekeys = ­1 if the header has not
yet been closed. Note that CFITSIO will dynamically add space if required when writing new
keywords to a header so in practice there is no limit to the number of keywords that can be
added to a header. A null pointer may be entered for the morekeys parameter if it's value is
not needed.
int fits—get—hdrspace / ffghsp
(fitsfile *fptr, ? int *keysexist, int *morekeys, int *status)
2 Write (append) a new keyword of the appropriate datatype into the CHU. Note that the address
to the value, and not the value itself, must be entered. The datatype parameter specifies the
datatype of the keyword value with one of the following values: TSTRING, TLOGICAL
(== int), TBYTE, TSHORT, TUSHORT, TINT, TUINT, TLONG, TULONG, TFLOAT,
TDOUBLE. A null pointer may be entered for the comment parameter which will cause the
comment field to be left blank.
int fits—write—key / ffpky
(fitsfile *fptr, int datatype, char *keyname, DTYPE *value,
char *comment, ? int *status)
3 Write (update) a keyword of the appropriate datatype into the CHU. This routine will modify
the value and comment field if the keyword already exists in the header, otherwise it will ap­
pend a new keyword at the end of the header. Note that the address to the value, and not the
value itself, must be entered. The datatype parameter specifies the datatype of the keyword
value and can have one of the following values: TSTRING, TLOGICAL (== int), TBYTE,
TSHORT, TUSHORT, TINT, TUINT, TLONG, TULONG, TFLOAT, TDOUBLE, TCOM­
PLEX, and TDBLCOMPLEX. A null pointer may be entered for the comment parameter
which will leave the comment field blank (or unmodified).
int fits—update—key / ffuky

72 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
(fitsfile *fptr, int datatype, char *keyname, DTYPE *value,
char *comment, ? int *status)
4 Write a keyword with a null or undefined value (i.e., the value field in the keyword is left blank).
This routine will modify the value and comment field if the keyword already exists in the
header, otherwise it will append a new null­valued keyword at the end of the header. A null
pointer may be entered for the comment parameter which will leave the comment field blank
(or unmodified).
int fits—update—key—null / ffukyu
(fitsfile *fptr, char *keyname, char *comment, ? int *status)
5 Write (append) a COMMENT keyword to the CHU. The comment string will be split over
multiple COMMENT keywords if it is longer than 70 characters.
int fits—write—comment / ffpcom
(fitsfile *fptr, char *comment, ? int *status)
6 Write (append) a HISTORY keyword to the CHU. The comment string will be split over multiple
HISTORY keywords if it is longer than 70 characters.
int fits—write—history / ffphis
(fitsfile *fptr, char *history, ? int *status)
7 Write the DATE keyword to the CHU. The keyword value will contain the current system date
as a character string in 'yyyy­mm­ddThh:mm:ss' format. If a DATE keyword already exists
in the header, then this routine will simply update the keyword value with the current date.
int fits—write—date / ffpdat
(fitsfile *fptr, ? int *status)
8 Write a user specified keyword record into the CHU. This is a low--level routine which can be
used to write any arbitrary record into the header. The record must conform to the all the
FITS format requirements.
int fits—write—record / ffprec
(fitsfile *fptr, char *card, ? int *status)
9 Update an 80­character record in the CHU. If a keyword with the input name already exists,
then it is overwritten by the value of card. This could modify the keyword name as well as
the value and comment fields. If the keyword doesn't already exist then a new keyword card
is appended to the header.

7.4. HEADER KEYWORD READ/WRITE ROUTINES 73
int fits—update—card / ffucrd
(fitsfile *fptr, char *keyname, char *card, ? int *status)
10 Write the physical units string into an existing keyword. This routine uses a local convention,
shown in the following example, in which the keyword units are enclosed in square brackets
in the beginning of the keyword comment field.
VELOCITY= 12.3 / [km/s] orbital speed
int fits—write—key—unit / ffpunt
(fitsfile *fptr, char *keyname, char *unit, ? int *status)
11 Rename an existing keyword preserving the current value and comment fields.
int fits—modify—name / ffmnam
(fitsfile *fptr, char *oldname, char *newname, ? int *status)
12 Modify (overwrite) the comment field of an existing keyword.
int fits—modify—comment / ffmcom
(fitsfile *fptr, char *keyname, char *comment, ? int *status)
13 Read the nth header record in the CHU. The first keyword in the header is at keynum = 1; if
keynum = 0 then this routine simply moves the internal CFITSIO pointer to the beginning
of the header so that subsequent keyword operations will start at the top of the header (e.g.,
prior to searching for keywords using wild cards in the keyword name).
int fits—read—record / ffgrec
(fitsfile *fptr, int keynum, ? char *card, int *status)
14 Read the header record having the specified keyword name.
int fits—read—card / ffgcrd
(fitsfile *fptr, char *keyname, ? char *card, int *status)
15 Read a specified keyword value and comment. The datatype parameter specifies the returned
datatype of the keyword value and can have one of the following symbolic constant values:
TSTRING, TLOGICAL (== int), TBYTE, TSHORT, TUSHORT, TINT, TUINT, TLONG,
TULONG, TFLOAT, TDOUBLE, TCOMPLEX, and TDBLCOMPLEX. Data type conver­
sion will be performed for numeric values if the keyword value does not have the same
datatype. If the value of the keyword is undefined (i.e., the value field is blank) then an
error status = VALUE UNDEFINED will be returned. If a NULL comment pointer is given
on input then the comment string will not be returned.

74 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
int fits—read—key / ffgky
(fitsfile *fptr, int datatype, char *keyname, ? DTYPE *value,
char *comment, int *status)
16 Read the physical units string in an existing keyword. This routine uses a local convention,
shown in the following example, in which the keyword units are enclosed in square brackets in
the beginning of the keyword comment field. A null string is returned if no units are defined
for the keyword.
VELOCITY= 12.3 / [km/s] orbital speed
int fits—read—key—unit / ffgunt
(fitsfile *fptr, char *keyname, ? char *unit, int *status)
17 Delete a keyword record. The space previously occupied by the keyword is reclaimed by mov­
ing all the following header records up one row in the header. The first routine deletes a
keyword at a specified position in the header (the first keyword is at position 1), whereas the
second routine deletes a specifically named keyword. Wild card characters may be used when
specifying the name of the keyword to be deleted.
int fits—delete—record / ffdrec
(fitsfile *fptr, int keynum, ? int *status)
int fits—delete—key / ffdkey
(fitsfile *fptr, char *keyname, ? int *status)
7.5 Iterator Routines
The use of these routines is described in the previous chapter. Most of these routines do not have
a corresponding short function name.
1 Iterator `constructor' functions that set the value of elements in the iteratorCol structure that
define the columns or arrays. These set the fitsfile pointer, column name, column number,
datatype, and iotype, respectively. The last 2 routines allow all the parameters to be set with
one function call (one supplies the column name, the other the column number).
int fits—iter—set—file(iteratorCol *col, fitsfile *fptr);
int fits—iter—set—colname(iteratorCol *col, char *colname);
int fits—iter—set—colnum(iteratorCol *col, int colnum);
int fits—iter—set—datatype(iteratorCol *col, int datatype);

7.5. ITERATOR ROUTINES 75
int fits—iter—set—iotype(iteratorCol *col, int iotype);
int fits—iter—set—by—name(iteratorCol *col, fitsfile *fptr,
char *colname, int datatype, int iotype);
int fits—iter—set—by—num(iteratorCol *col, fitsfile *fptr,
int colnum, int datatype, int iotype);
2 Iterator `accessor' functions that return the value of the element in the iteratorCol structure
that describes a particular data column or array
fitsfile * fits—iter—get—file(iteratorCol *col);
char * fits—iter—get—colname(iteratorCol *col);
int fits—iter—get—colnum(iteratorCol *col);
int fits—iter—get—datatype(iteratorCol *col);
int fits—iter—get—iotype(iteratorCol *col);
void * fits—iter—get—array(iteratorCol *col);
long fits—iter—get—tlmin(iteratorCol *col);
long fits—iter—get—tlmax(iteratorCol *col);
long fits—iter—get—repeat(iteratorCol *col);
char * fits—iter—get—tunit(iteratorCol *col);
char * fits—iter—get—tdisp(iteratorCol *col);
3 The CFITSIO iterator function
int fits—iterate—data(int narrays, iteratorCol *data, long offset,
long nPerLoop,
int (*workFn)( long totaln, long offset, long firstn,
long nvalues, int narrays, iteratorCol *data,
void *userPointer),
void *userPointer,
int *status);

76 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
7.6 Primary Array or IMAGE Extension I/O Routines
These routines read or write data values in the primary data array (i.e., the first HDU in a FITS
file) or an IMAGE extension. These routines simply treat the array as a long 1­dimensional array of
pixels ignoring the intrinsic dimensionality of the array as defined by the NAXISn keywords. When
dealing with a 2D image, for example, the application program must calculate the pixel offset in
the 1­D array that corresponds to any particular X, Y coordinate in the image. C programmers
should note that the ordering of arrays in FITS files, and hence in all the CFITSIO calls, is more
similar to the dimensionality of arrays in Fortran rather than C. For instance if a FITS image has
NAXIS1 = 100 and NAXIS2 = 50, then a 2­D array just large enough to hold the image should be
declared as array[50][100] and not as array[100][50].
The `datatype' parameter specifies the datatype of the `nulval' and `array' pointers and can have
one of the following values: TBYTE, TSHORT, TUSHORT, TINT, TUINT, TLONG, TULONG,
TFLOAT, TDOUBLE. Automatic data type conversion is performed if the data type of the FITS
array (as defined by the BITPIX keyword) differs from that specified by 'datatype'. The data
values are also automatically scaled by the BSCALE and BZERO keyword values as they are being
read or written in the FITS array.
1 Get the data type of the image (= BITPIX value). Possible returned values are: BYTE IMG
(8), SHORT IMG (16), LONG IMG (32), FLOAT IMG (­32), or DOUBLE IMG (­64).
int fits—get—img—type / ffgidt
(fitsfile *fptr, ? int *bitpix, int *status)
2 Get the dimension (number of axes = NAXIS) of the image
int fits—get—img—dim / ffgidm
(fitsfile *fptr, ? int *naxis, int *status)
3 Get the size of all the dimensions of the image
int fits—get—img—size / ffgisz
(fitsfile *fptr, int maxdim, ? long *naxes, int *status)
4 Get the parameters that define the type and size of the image. This routine simply combines
calls to the above 3 routines.
int fits—get—img—param / ffgipr
(fitsfile *fptr, int maxdim, ? int *bitpix, int *naxis, long *naxes,
int *status)
5 Write elements into the FITS data array.

7.7. ASCII AND BINARY TABLE ROUTINES 77
int fits—write—img / ffppr
(fitsfile *fptr, int datatype, long firstelem, long nelements,
DTYPE *array, int *status);
6 Write elements into the FITS data array, substituting the appropriate FITS null value for all
elements which are equal to the input value of nulval (note that this parameter gives the
address of the null value, not the null value itself). For integer FITS arrays, the FITS null
value is defined by the BLANK keyword (an error is returned if the BLANK keyword doesn't
exist). For floating point FITS arrays the special IEEE NaN (Not­a­Number) value will be
written into the FITS file. If a null pointer is entered for nulval, then the null value is ignored
and this routine behaves the same as fits write img.
int fits—write—imgnull / ffppn
(fitsfile *fptr, int datatype, long firstelem, long nelements,
DTYPE *array, DTYPE *nulval, ? int *status);
7 Set FITS data array elements equal to the appropriate null pixel value. For integer FITS arrays,
the FITS null value is defined by the BLANK keyword (an error is returned if the BLANK
keyword doesn't exist). For floating point FITS arrays the special IEEE NaN (Not­a­Number)
value will be written into the FITS file.
int fits—write—null—img / ffpprn
(fitsfile *fptr, long firstelem, long nelements, ? int *status)
8 Read elements from the FITS data array. Undefined FITS array elements will be returned with
a value = *nullval, (note that this parameter gives the address of the null value, not the null
value itself) unless nulval = 0 or *nulval = 0, in which case no checks for undefined pixels
will be performed.
int fits—read—img / ffgpv
(fitsfile *fptr, int datatype, long firstelem, long nelements,
DTYPE *nulval, ? DTYPE *array, int *anynul, int *status)
9 Read elements from the FITS data array. Any undefined FITS array elements will have the
corresponding nullarray element set to TRUE.
int fits—read—imgnull / ffgpf
(fitsfile *fptr, int datatype, long firstelem, long nelements,
? DTYPE *array, char *nullarray, int *anynul, int *status)
7.7 ASCII and Binary Table Routines
These routines perform read and write operations on columns of data in FITS ASCII or Binary
tables. Note that in the following discussions, the first row and column in a table is at position 1
not 0.

78 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
7.7.1 Column Information Routines
1 Get the number of rows or columns in the current FITS table. The number of rows is given by
the NAXIS2 keyword and the number of columns is given by the TFIELDS keyword in the
header of the table.
int fits—get—num—rows / ffgnrw
(fitsfile *fptr, ? long *nrows, int *status);
int fits—get—num—cols / ffgncl
(fitsfile *fptr, ? int *ncols, int *status);
2 Get the table column number (and name) of the column whose name matches an input template
name. If casesen = CASESEN then the column name match will be case­sensitive, whereas
if casesen = CASEINSEN then the case will be ignored. As a general rule, the column names
should be treated as case INsensitive.
The input column name template may be either the exact name of the column to be searched
for, or it may contain wild card characters (*, ?, or #), or it may contain the integer number
of the desired column (with the first column = 1). The `*' wild card character matches any
sequence of characters (including zero characters) and the `?' character matches any single
character. The # wildcard will match any consecutive string of decimal digits (0­9). If more
than one column name in the table matches the template string, then the first match is
returned and the status value will be set to COL NOT UNIQUE as a warning that a unique
match was not found. To find the other cases that match the template, call the routine again
leaving the input status value equal to COL NOT UNIQUE and the next matching name will
then be returned. Repeat this process until a status = COL NOT FOUND is returned.
The FITS Standard recommends that only letters, digits, and the underscore character be
used in column names (with no embedded spaces). Trailing blank characters are not signif­
icant. It is recommended that all the column names in a given table be unique within the
first 8 characters, and strongly recommended that the names be unique within the first 16
characters.
int fits—get—colnum / ffgcno
(fitsfile *fptr, int casesen, char *templt, ? int *colnum,
int *status)
int fits—get—colname / ffgcnn
(fitsfile *fptr, int casesen, char *templt, ? char *colname,
int *colnum, int *status)
3 Return the datatype and vector repeat value for a column in an ASCII or binary table. Allowed
values for the datatype in ASCII tables are: TSTRING, TSHORT, TLONG, TFLOAT, and
TDOUBLE. Binary tables also support these types: TLOGICAL, TBIT, TBYTE, TCOM­
PLEX and TDBLCOMPLEX. Note that if the column is a 32­bit integer, then this routine

7.7. ASCII AND BINARY TABLE ROUTINES 79
will return datatype = TLONG regardless of the length of a long integers on that machine
(i.e., even on DEC Alpha OSF machines in which long integers are 8 bytes long). The nega­
tive of the datatype code value is returned if it is a variable length array column. The vector
repeat count is always 1 for ASCII table columns. If the specified column has an ASCII
character datatype (code = TSTRING) then the width of a unit string in the column is also
returned. Note that this routine supports the local convention for specifying arrays of fixed
length strings within a binary table character column using the syntax TFORM = 'rAw'
where 'r' is the total number of characters (= the width of the column) and 'w' is the width
of a unit string within the column. Thus if the column has TFORM = '60A12' then this
routine will return typecode = TSTRING, repeat = 60, and width = 12. A null pointer may
be given for any of the output parameters that are not needed.
int fits—get—coltype / ffgtcl
(fitsfile *fptr, int colnum, ? int *typecode, long *repeat,
long *width, int *status)
4 Return the display width of a column. This is the length of the string that will be returned by
the fits read col routine when reading the column as a formatted string. The display width
is determined by the TDISPn keyword, if present, otherwise by the data type of the column.
int fits—get—col—display—width / ffgcdw
(fitsfile *fptr, int colnum, ? int *dispwidth, int *status)
5 Write (append) a TDIMn keyword whose value has the form '(l,m,n...)' where l, m, n... are the
dimensions of a multidimension array column in a binary table.
int fits—write—tdim / ffptdm
(fitsfile *fptr, int colnum, int naxis, long *naxes, ? int *status)
6 Return the number of and size of the dimensions of a table column in a binary table. Normally
this information is given by the TDIMn keyword, but if this keyword is not present then this
routine returns naxis = 1 and naxes[0] equal to the repeat count in the TFORM keyword.
int fits—read—tdim / ffgtdm
(fitsfile *fptr, int colnum, int maxdim, ? int *naxis,
long *naxes, int *status)
7 Decode the input TDIMn keyword string (e.g. '(100,200)') and return the number of and size
of the dimensions of a binary table column. If the input tdimstr character string is null, then
this routine returns naxis = 1 and naxes[0] equal to the repeat count in the TFORM keyword.
This routine is called by fits read tdim.
int fits—decode—tdim / ffdtdm
(fitsfile *fptr, char *tdimstr, int colnum, int maxdim, ? int *naxis,
long *naxes, int *status)

80 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
7.7.2 Routines to Edit Rows or Columns
1 Insert blank rows into an ASCII or binary table. All the rows following row FROW are shifted
down by NROWS rows. If FROW = 0 then the blank rows are inserted at the beginning of
the table. This routine updates the NAXIS2 keyword to reflect the new number of rows in
the table.
int fits—insert—rows / ffirow
(fitsfile *fptr, long firstrow, long nrows, ? int *status)
2 Delete rows from an ASCII or binary table (in the CDU). The NROWS number of rows are
deleted, starting with row FROW. Any remaining rows in the table are shifted up to fill in
the space. This routine modifies the NAXIS2 keyword to reflect the new number of rows in
the table. The physical size of the FITS file may not be reduced by this operation, in which
case the empty FITS blocks if anyat the end of the file will be padded with zeros.
int fits—delete—rows / ffdrow
(fitsfile *fptr, long firstrow, long nrows, ? int *status)
3 Delete a list of rows from an ASCII or binary table (in the CDU). rowlist is an array of row
numbers to be deleted from the table. (The first row in the table is 1 not 0). The list of row
numbers must be sorted in ascending order. nrows is the number of row numbers in the list.
The physical size of the FITS file may not be reduced by this operation, in which case the
empty FITS blocks if any at the end of the file will be padded with zeros.
int fits—delete—rowlist / ffdrws
(fitsfile *fptr, long *rowlist, long nrows, ? int *status)
4 Insert a blank column (or columns) into an ASCII or binary table. COLNUM specifies the
column number that the (first) new column should occupy in the table. NCOLS speci­
fies how many columns are to be inserted. Any existing columns from this position and
higher are shifted over to allow room for the new column(s). The index number on all
the following keywords will be incremented if necessary to reflect the new position of the
column(s) in the table: TBCOLn, TFORMn, TTYPEn, TUNITn, TNULLn, TSCALn, TZE­
ROn, TDISPn, TDIMn, TLMINn, TLMAXn, TDMINn, TDMAXn, TCTYPn, TCRPXn,
TCRVLn, TCDLTn, TCROTn, and TCUNIn.
int fits—insert—col / fficol
(fitsfile *fptr, int colnum, char *ttype, char *tform,
? int *status)
int fits—insert—cols / fficls
(fitsfile *fptr, int colnum, int ncols, char **ttype,
char **tform, ? int *status)

7.7. ASCII AND BINARY TABLE ROUTINES 81
5 Modify the vector length of a binary table column (e.g., change a column from TFORMn =
'1E' to '20E'). The vector length may be increased or decreased from the current value.
int fits—modify—vector—len / ffmvec
(fitsfile *fptr, int colnum, long newveclen, ? int *status)
6 Delete a column from an ASCII or binary table (in the CDU). The index number of all the
keywords listed above will be decremented if necessary to reflect the new position of the
column(s) in the table. The physical size of the FITS file may not be reduced by this operation,
and the empty FITS blocks if any at the end of the file will be padded with zeros.
int fits—delete—col / ffdcol(fitsfile *fptr, int colnum, ? int *status)
7 Copy a column from one HDU to another (or to the same HDU). If create col = TRUE, then a
new column will be inserted in the output table, at position `outcolumn', otherwise the existing
output column will be overwritten (in which case it must have a compatible datatype). Note
that the first column in a table is at colnum = 1.
int fits—copy—col / ffcpcl
(fitsfile *infptr, fitsfile *outfptr, int incolnum, int outcolnum,
int create—col, ? int *status);
7.7.3 Read and Write Column Data Routines
The following routines write or read data values in the current ASCII or binary table extension.
If a write operation extends beyond the current size of the table, then the number of rows in the
table will automatically be increased and the NAXIS2 keyword value will be updated. Attempts
to read beyond the end of the table will result in an error.
Automatic data type conversion is performed for numerical data types (only) if the data type of the
column (defined by the TFORMn keyword) differs from the data type of the calling routine. ASCII
tables support the following datatype values: TSTRING, TBYTE, TSHORT, TUSHORT, TINT,
TUINT, TLONG, TULONG, TFLOAT, or TDOUBLE. Binary tables also support TLOGICAL
(internally mapped to the `char' datatype), TCOMPLEX, and TDBLCOMPLEX.
Numerical data values are automatically scaled by the TSCALn and TZEROn keyword values (if
they exist).
In the case of binary tables with vector elements, the 'felem' parameter defines the starting pixel
within the cell (a cell is defined as the intersection of a row and a column and may contain a
single value or a vector of values). The felem parameter is ignored when dealing with ASCII tables.
Similarly, in the case of binary tables the 'nelements' parameter specifies the total number of vector
values to be read or written (continuing on subsequent rows if required) and not the number of
table cells.
1 Write elements into an ASCII or binary table column.

82 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
int fits—write—col / ffpcl
(fitsfile *fptr, int datatype, int colnum, long firstrow,
long firstelem, long nelements, DTYPE *array, ? int *status)
2 Write elements into an ASCII or binary table column, substituting the appropriate FITS null
value for any elements that are equal to the nulval parameter (note that this parameter gives
the address of the null value, not the null value itself). For all ASCII table columns and
for integer columns in binary tables, the null value to be used in the FITS file is defined by
the TNULLn keyword and an error is returned if the TNULLn keyword doesn't exist. For
floating point columns in binary tables the special IEEE NaN (Not­a­Number) value will be
written into the FITS column. If a null pointer is entered for nulval, then the null value is
ignored and this routine behaves the same as fits write col. This routine must not be used to
write to variable length array columns.
int fits—write—colnul / ffpcn
(fitsfile *fptr, int datatype, int colnum, long firstrow,
long firstelem, long nelements, DTYPE *array, DTYPE *nulval,
? int *status)
3 Set elements in a table column as undefined. For all ASCII table columns and for integer
columns in binary tables, the null value to be used in the FITS file is defined by the TNULLn
keyword and an error is returned if the TNULLn keyword doesn't exist. For floating point
columns in binary tables the special IEEE NaN (Not­a­Number) value will be written into
the FITS column.
int fits—write—col—null / ffpclu
(fitsfile *fptr, int colnum, long firstrow, long firstelem,
long nelements, ? int *status)
4 Read elements from an ASCII or binary table column. The datatype parameter specifies the
datatype of the `nulval' and `array' pointers; Undefined array elements will be returned with
a value = *nullval, (note that this parameter gives the address of the null value, not the null
value itself) unless nulval = 0 or *nulval = 0, in which case no checking for undefined pixels
will be performed.
Any column, regardless of it's intrinsic datatype, may be read as a string. It should be noted
however that reading a numeric column as a string is 10 ­ 100 times slower than reading the
same column as a number due to the large overhead in constructing the formatted strings. The
display format of the returned strings will be determined by the TDISPn keyword, if it exists,
otherwise by the datatype of the column. The length of the returned strings (not including
the null terminating character) can be determined with the fits get col display width routine.
The following TDISPn display formats are currently supported:

7.8. CELESTIAL COORDINATE SYSTEM ROUTINES 83
Iw.m Integer
Ow.m Octal integer
Zw.m Hexadecimal integer
Fw.d Fixed floating point
Ew.d Exponential floating point
Dw.d Exponential floating point
Gw.d General; uses Fw.d if significance not lost, else Ew.d
where w is the width in characters of the displayed values, m is the minimum number of digits
displayed, and d is the number of digits to the right of the decimal. The .m field is optional.
int fits—read—col / ffgcv
(fitsfile *fptr, int datatype, int colnum, long firstrow, long firstelem,
long nelements, DTYPE *nulval, DTYPE *array, int *anynul, int *status)
5 Read elements from an ASCII or binary table column. The datatype parameter specifies the
datatype of the and `array' pointer; Any undefined elements will have the corresponding
nullarray element set to TRUE.
int fits—read—colnull / ffgcf
(fitsfile *fptr, int datatype, int colnum, long firstrow, long firstelem,
long nelements, DTYPE *array, char *nullarray, int *anynul, int *status)
7.8 Celestial Coordinate System Routines
Two complimentary sets of routines are provided for calculating the transformation between pixel
location in an image and the the corresponding celestial coordinates on the sky. These routines rely
on a set of standard World Coordinate System (WCS) keywords in the header of the HDU which
define the parameters to be used when calculating the coordinate transformation.
Both sets of routines require that a 2 step procedure be followed: first an initialization routine must
be called to read the relevent WCS keywords in the header. These parameters are then passed to
a pair of routines that convert from pixel to sky coordinates, or from sky to pixel coordinates.
The first set of routines described below have the advantage that they are completely self­contained
within the CFITSIO library and thus are guaranteed to be available on the system. These routines
only support the most common types of map projections and WCS keyword conventions however.
The second set of routines are available in a WCS library written by Doug Mink at SAO. These
routines are more powerful than the ones contained in CFITSIO itself because they support all the
defined WCS map projections and they support a number of non­standard keyword conventions
that have been adopted over the years by various different observatories. To use these routines,
however, requires that a separate WCS library be built and installed on the system in addition to
CFITSIO.

84 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
7.8.1 Self­contained WCS Routines
The following routines are included in the CFITSIO library to help calculate the transformation
between pixel location in an image and the corresponding celestial coordinates on the sky. These
support the following standard map projections: ­SIN, ­TAN, ­ARC, ­NCP, ­GLS, ­MER, and ­
AIT (these are the legal values for the coordtype parameter). These routines are based on similar
functions in Classic AIPS. All the angular quantities are given in units of degrees.
1 Get the values of all the standard FITS celestial coordinate system keywords from the header
of a FITS image (i.e., the primary array or an image extension). These values may then be
passed to the routines that perform the coordinate transformations. If any or all of the WCS
keywords are not present, then default values will be returned. If the first coordinate axis is
the declination­like coordinate, then this routine will swap them so that the longitudinal­like
coordinate is returned as the first axis.
If the file uses the newer 'CDj i' WCS transformation matrix keywords instead of old style
'CDELTn' and 'CROTA2' keywords, then this routine will calculate and return the values
of the equivalent old­style keywords. Note that the conversion from the new­style keywords
to the old­style values is sometimes only an approximation, so if the approximation is larger
than an internally defined threshold level, then CFITSIO will still return the approximate
WCS keyword values, but will also return with status = APPROX WCS KEY, to warn the
calling program that approximations have been made. It is then up to the calling program
to decide whether the approximations are sufficiently accurate for the particular application,
or whether more precise WCS transformations must be performed using new­style WCS
keywords directly.
int fits—read—img—coord / ffgics
(fitsfile *fptr, ? double *xrefval, double *yrefval,
double *xrefpix, double *yrefpix, double *xinc, double *yinc,
double *rot, char *coordtype, int *status)
2 Get the values of all the standard FITS celestial coordinate system keywords from the header
of a FITS table where the X and Y (or RA and DEC coordinates are stored in 2 separate
columns of the table. These values may then be passed to the routines that perform the
coordinate transformations.
int fits—read—tbl—coord / ffgtcs
(fitsfile *fptr, int xcol, int ycol, ? double *xrefval,
double *yrefval, double *xrefpix, double *yrefpix, double *xinc,
double *yinc, double *rot, char *coordtype, int *status)
3 Calculate the celestial coordinate corresponding to the input X and Y pixel location in the
image.
int fits—pix—to—world / ffwldp

7.8. CELESTIAL COORDINATE SYSTEM ROUTINES 85
(double xpix, double ypix, double xrefval, double yrefval,
double xrefpix, double yrefpix, double xinc, double yinc,
double rot, char *coordtype, ? double *xpos, double *ypos,
int *status)
4 Calculate the X and Y pixel location corresponding to the input celestial coordinate in the
image.
int fits—world—to—pix / ffxypx
(double xpos, double ypos, double xrefval, double yrefval,
double xrefpix, double yrefpix, double xinc, double yinc,
double rot, char *coordtype, double *xpix, double *ypix,
int *status)
7.8.2 WCS Routines that require the WCS library
The routines described in this section use the WCS library written by Doug Mink at SAO. This
library is available at
http://tdc­www.harvard.edu/software/wcstools/ and
http://tdc­www.harvard.edu/software/wcstools/wcs.html
You do not need the entire WCSTools package to use the routines described here. Instead, you only
need to install the World Coordinate System Subroutine library. It is available from the ftp site as
a gzipped .tar file (e.g., wcssubs­2.5.tar.gz) or as a zipped file (e.g., wcssub25.zip). Any questions
about using this library should be sent to the author at dmink@cfa.harvard.edu.
The advantage of using the WCS library instead of the self­contained WCS routines decribed in
the previous section is that they provide support for all currently defined projection geometries,
and they also support most standard as well as many non­standard WCS keyword conventions that
have been used by different observatories in the past. This library is also actively maintained so
it is likely that it will support any new FITS WCS keyword conventions that are adopted in the
future.
The first 3 routines described below are CFITSIO routines that create a character string array
containing all the WCS keywords that are needed as input to the WCS library 'wcsinit' routine.
These 3 routines provide a convenient interface for calling the WCS library routines from CFITSIO,
but do not actually call any routines in the WCS library themselves.
1 Copy all the WCS­related keywords from the header of the primary array or an image ex­
tension into a single long character string array. The 80­char header keywords are simply
concatinated one after the other in the returned string. The character array is dynamically
allocated and must be freed by the calling program when it is no longer needed. In the current
implementation, all the header keywords are copied into the array.

86 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
int fits—get—image—wcs—keys / ffgiwcs
(fitsfile *fptr, char **header, int *status)
2 Copy all the WCS­related keywords for a given pair of columns in a table extension into a
single long character string array. The pair of columns must contain a list of the X and Y
coordinates of each event in the image (i.e., this is an image in pixel­list or event­list format).
The names of the WCS keywords in the table header are translated into the keywords that
would correspond to an image HDU (e.g., TCRPXn for the X column becomes the CRPIX1
keyword). The 80­char header keywords are simply concatinated one after the other in the
string. The character array is dynamically allocated and must be freed by the calling program
when it is no longer needed.
int fits—get—table—wcs—keys / ffgtwcs
(fitsfile *fptr, int xcol, int ycol, char **header, int *status)
3 Copy all the WCS­related keywords for an image that is contained in a single vector cell of
a binary table extension into a single long character string array. In this type of image
format, the table column is a 2­dimensional vector and each row of the table contains an
image. The names of the WCS keywords in the table header are translated into the keywords
corresponding to an image (e.g., 1CRPn becomes the CRPIX1 keyword). The 80­char header
keywords are simply concatinated one after the other in the string. The character array is
dynamically allocated and must be freed by the calling program when it is no longer needed.
int fits—get—imagecell—wcs—keys / ffgicwcs
(fitsfile *fptr, int column, long row, char **header, int *status)
4 This WCS library routine returns a pointer to a structure that contains all the WCS parameters
extracted from the input header keywords. The input header keyword string can be produced
by any of the 3 previous routines. The returned WorldCoor structure is used as input to the
next 2 WCS library routines that convert between sky coordinates and pixel coordinates.
This routine dynamically allocates the WorldCoor structure, so it must be freed by calling
the wcsfree routine when it is no longer needed.
struct WorldCoor *wcsinit (char *header)
5 Calculate the sky coordinate corresponding to the input pixel coordinate using the conversion
parameters defined in the wcs structure. This is a WCS library routine.
void pix2wcs (struct WorldCoor *wcs, double xpix, double ypix,
? double *xpos, double *ypos)
6 Calculate the pixel coordinate corresponding to the input sky coordinate using the conversion
parameters defined in the wcs structure. The returned offscale parameter equals 0 if the
coordinate is within bounds of the image. This is a WCS library routine.

7.9. HIERARCHICAL GROUPING CONVENTION SUPPORT ROUTINES 87
void wcs2pix (struct WorldCoor *wcs, double xpos, double ypos,
? double *xpix, double *ypix, int *offscale)
7 Free the WCS structure that was created by wcsinit. This is a WCS library routine.
void wcsfree(struct WorldCoor *wcs)
7.9 Hierarchical Grouping Convention Support Routines
These functions allow for the creation and manipulation of FITS HDU Groups, as defined in ''A
Hierarchical Grouping Convention for FITS'' by Jennings, Pence, Folk and Schlesinger ( http: //ad­
fwww.gsfc.nasa.gov/other/convert/group.html ). A group is a collection of HDUs whose association
is defined by a grouping table. HDUs which are part of a group are referred to as member HDUs
or simply as members. Grouping table member HDUs may themselves be grouping tables, thus
allowing for the construction of open­ended hierarchies of HDUs.
Grouping tables contain one row for each member HDU. The grouping table columns provide iden­
tification information that allows applications to reference or ''point to'' the member HDUs. Mem­
ber HDUs are expected, but not required, to contain a set of GRPIDn/GRPLCn keywords in their
headers for each grouping table that they are referenced by. In this sense, the GRPIDn/GRPLCn
keywords ''link'' the member HDU back to its Grouping table. Note that a member HDU need not
reside in the same FITS file as its grouping table, and that a given HDU may be referenced by up
to 999 grouping tables simultaneously.
Grouping tables are implemented as FITS binary tables with up to six pre­defined column TTYPEn
values: 'MEMBER XTENSION', 'MEMBER NAME', 'MEMBER VERSION', 'MEMBER POSITION',
'MEMBER URI TYPE' and 'MEMBER LOCATION'. The first three columns allow member HDUs
to be identified by reference to their XTENSION, EXTNAME and EXTVER keyword values. The
fourth column allows member HDUs to be identified by HDU position within their FITS file. The
last two columns identify the FITS file in which the member HDU resides, if different from the
grouping table FITS file.
Additional user defined ''auxiliary'' columns may also be included with any grouping table. When a
grouping table is copied or modified the presence of auxiliary columns is always taken into account
by the grouping support functions; however, the grouping support functions cannot directly make
use of this data.
If a grouping table column is defined but the corresponding member HDU information is un­
available then a null value of the appropriate data type is inserted in the column field. Integer
columns (MEMBER POSITION, MEMBER VERSION) are defined with a TNULLn value of zero
(0). Character field columns (MEMBER XTENSION, MEMBER NAME, MEMBER URI TYPE,
MEMBER LOCATION) utilize an ASCII null character to denote a null field value.
The grouping support functions belong to two basic categories: those that work with grouping table
HDUs (ffgt**) and those that work with member HDUs (ffgm**). Two functions, fits copy group()
and fits remove group(), have the option to recursively copy/delete entire groups. Care should

88 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
be taken when employing these functions in recursive mode as poorly defined groups could cause
unpredictable results. The problem of a grouping table directly or indirectly referencing itself (thus
creating an infinite loop) is protected against; in fact, neither function will attempt to copy or
delete an HDU twice.
1 Create (append) a grouping table at the end of the current FITS file pointed to by fptr. The
grpname parameter provides the grouping table name (GRPNAME keyword value) and may
be set to NULL if no group name is to be specified. The grouptype parameter specifies
the desired structure of the grouping table and may take on the values: GT ID ALL URI
(all columns created), GT ID REF (ID by reference columns), GT ID POS (ID by position
columns), GT ID ALL (ID by reference and position columns), GT ID REF URI (ID by
reference and FITS file URI columns), and GT ID POS URI (ID by position and FITS file
URI columns).
int fits—create—group / ffgtcr
(fitsfile *fptr, char *grpname, int grouptype, ? int *status)
2 Create (insert) a grouping table just after the CHDU of the current FITS file pointed to by fptr.
All HDUs below the the insertion point will be shifted downwards to make room for the new
HDU. The grpname parameter provides the grouping table name (GRPNAME keyword value)
and may be set to NULL if no group name is to be specified. The grouptype parameter speci­
fies the desired structure of the grouping table and may take on the values: GT ID ALL URI
(all columns created), GT ID REF (ID by reference columns), GT ID POS (ID by position
columns), GT ID ALL (ID by reference and position columns), GT ID REF URI (ID by ref­
erence and FITS file URI columns), and GT ID POS URI (ID by position and FITS file URI
columns) .
int fits—insert—group / ffgtis
(fitsfile *fptr, char *grpname, int grouptype, ? int *status)
3 Change the structure of an existing grouping table pointed to by gfptr. The grouptype parameter
(see fits create group() for valid parameter values) specifies the new structure of the grouping
table. This function only adds or removes grouping table columns, it does not add or delete
group members (i.e., table rows). If the grouping table already has the desired structure then
no operations are performed and function simply returns with a (0) success status code. If
the requested structure change creates new grouping table columns, then the column values
for all existing members will be filled with the null values appropriate to the column type.
int fits—change—group / ffgtch
(fitsfile *gfptr, int grouptype, ? int *status)
4 Remove the group defined by the grouping table pointed to by gfptr, and optionally all the
group member HDUs. The rmopt parameter specifies the action to be taken for all members

7.9. HIERARCHICAL GROUPING CONVENTION SUPPORT ROUTINES 89
of the group defined by the grouping table. Valid values are: OPT RM GPT (delete only the
grouping table) and OPT RM ALL (recursively delete all HDUs that belong to the group).
Any groups containing the grouping table gfptr as a member are updated, and if rmopt ==
OPT RM GPT all members have their GRPIDn and GRPLCn keywords updated accordingly.
If rmopt == OPT RM ALL, then other groups that contain the deleted members of gfptr
are updated to reflect the deletion accordingly.
int fits—remove—group / ffgtrm
(fitsfile *gfptr, int rmopt, ? int *status)
5 Copy (append) the group defined by the grouping table pointed to by infptr, and optionally all
group member HDUs, to the FITS file pointed to by outfptr. The cpopt parameter specifies
the action to be taken for all members of the group infptr. Valid values are: OPT GCP GPT
(copy only the grouping table) and OPT GCP ALL (recursively copy ALL the HDUs that
belong to the group defined by infptr). If the cpopt == OPT GCP GPT then the members of
infptr have their GRPIDn and GRPLCn keywords updated to reflect the existence of the new
grouping table outfptr, since they now belong to the new group. If cpopt == OPT GCP ALL
then the new grouping table outfptr only contains pointers to the copied member HDUs and
not the original member HDUs of infptr. Note that, when cpopt == OPT GCP ALL, all
members of the group defined by infptr will be copied to a single FITS file pointed to by
outfptr regardless of their file distribution in the original group.
int fits—copy—group / ffgtcp
(fitsfile *infptr, fitsfile *outfptr, int cpopt, ? int *status)
6 Merge the two groups defined by the grouping table HDUs infptr and outfptr by combining
their members into a single grouping table. All member HDUs (rows) are copied from infptr
to outfptr. If mgopt == OPT MRG COPY then infptr continues to exist unaltered after the
merge. If the mgopt == OPT MRG MOV then infptr is deleted after the merge. In both
cases, the GRPIDn and GRPLCn keywords of the member HDUs are updated accordingly.
int fits—merge—groups / ffgtmg
(fitsfile *infptr, fitsfile *outfptr, int mgopt, ? int *status)
7 ''Compact'' the group defined by grouping table pointed to by gfptr. The compaction is achieved
by merging (via fits merge groups()) all direct member HDUs of gfptr that are themselves
grouping tables. The cmopt parameter defines whether the merged grouping table HDUs
remain after merging (cmopt == OPT CMT MBR) or if they are deleted after merging
(cmopt == OPT CMT MBR DEL). If the grouping table contains no direct member HDUs
that are themselves grouping tables then this function does nothing. Note that this function
is not recursive, i.e., only the direct member HDUs of gfptr are considered for merging.
int fits—compact—group / ffgtcm
(fitsfile *gfptr, int cmopt, ? int *status)

90 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
8 Verify the integrity of the grouping table pointed to by gfptr to make sure that all group members
are accessible and that all links to other grouping tables are valid. The firstfailed parameter
returns the member ID (row number) of the first member HDU to fail verification (if positive
value) or the first group link to fail (if negative value). If gfptr is successfully verified then
firstfailed contains a return value of 0.
int fits—verify—group / ffgtvf
(fitsfile *gfptr, ? long *firstfailed, int *status)
9 Open a grouping table that contains the member HDU pointed to by mfptr. The grouping table
to open is defined by the grpid parameter, which contains the keyword index value of the
GRPIDn/GRPLCn keyword(s) that link the member HDU mfptr to the grouping table. If
the grouping table resides in a file other than the member HDUs file then an attempt is first
made to open the file readwrite, and failing that readonly. A pointer to the opened grouping
table HDU is returned in gfptr.
Note that it is possible, although unlikely and undesirable, for the GRPIDn/GRPLCn key­
words in a member HDU header to be non­continuous, e.g., GRPID1, GRPID2, GRPID5,
GRPID6. In such cases, the grpid index value specified in the function call shall identify the
(grpid)th GRPID value. In the above example, if grpid == 3, then the group specified by
GRPID5 would be opened.
int fits—open—group / ffgtop
(fitsfile *mfptr, int group, ? fitsfile **gfptr, int *status)
10 Add a member HDU to an existing grouping table pointed to by gfptr. The member HDU
may either be pointed to mfptr (which must be positioned to the member HDU) or, if mfptr
== NULL, identified by the hdupos parameter (the HDU position number, Primary array
== 1) if both the grouping table and the member HDU reside in the same FITS file. The
new member HDU shall have the appropriate GRPIDn and GRPLCn keywords created in its
header. Note that if the member HDU is already a member of the group then it will not be
added a second time.
int fits—add—group—member / ffgtam
(fitsfile *gfptr, fitsfile *mfptr, int hdupos, ? int *status)
11 Return the number of member HDUs in a grouping table gfptr. The number member HDUs is
just the NAXIS2 value (number of rows) of the grouping table.
int fits—get—num—members / ffgtnm
(fitsfile *gfptr, ? long *nmembers, int *status)
12 Return the number of groups to which the HDU pointed to by mfptr is linked, as defined by
the number of GRPIDn/GRPLCn keyword records that appear in its header. Note that each

7.9. HIERARCHICAL GROUPING CONVENTION SUPPORT ROUTINES 91
time this function is called, the indices of the GRPIDn/GRPLCn keywords are checked to
make sure they are continuous (ie no gaps) and are re­enumerated to eliminate gaps if found.
int fits—get—num—groups / ffgmng
(fitsfile *mfptr, ? long *nmembers, int *status)
13 Open a member of the grouping table pointed to by gfptr. The member to open is identified by
its row number within the grouping table as given by the parameter 'member' (first member
== 1) . A fitsfile pointer to the opened member HDU is returned as mfptr. Note that if the
member HDU resides in a FITS file different from the grouping table HDU then the member
file is first opened readwrite and, failing this, opened readonly.
int fits—open—member / ffgmop
(fitsfile *gfptr, long member, ? fitsfile **mfptr, int *status)
14 Copy (append) a member HDU of the grouping table pointed to by gfptr. The member HDU
is identified by its row number within the grouping table as given by the parameter 'member'
(first member == 1). The copy of the group member HDU will be appended to the FITS
file pointed to by mfptr, and upon return mfptr shall point to the copied member HDU. The
cpopt parameter may take on the following values: OPT MCP ADD which adds a new entry
in gfptr for the copied member HDU, OPT MCP NADD which does not add an entry in gfptr
for the copied member, and OPT MCP REPL which replaces the original member entry with
the copied member entry.
int fits—copy—member / ffgmcp
(fitsfile *gfptr, fitsfile *mfptr, long member, int cpopt, ? int *status)
15 Transfer a group member HDU from the grouping table pointed to by infptr to the grouping
table pointed to by outfptr. The member HDU to transfer is identified by its row number
within infptr as specified by the parameter 'member' (first member == 1). If tfopt ==
OPT MCP ADD then the member HDU is made a member of outfptr and remains a member
of infptr. If tfopt == OPT MCP MOV then the member HDU is deleted from infptr after
the transfer to outfptr.
int fits—transfer—member / ffgmtf
(fitsfile *infptr, fitsfile *outfptr, long member, int tfopt,
? int *status)
16 Remove a member HDU from the grouping table pointed to by gfptr. The member HDU to be
deleted is identified by its row number in the grouping table as specified by the parameter
'member' (first member == 1). The rmopt parameter may take on the following values:
OPT RM ENTRY which removes the member HDU entry from the grouping table and up­
dates the member's GRPIDn/GRPLCn keywords, and OPT RM MBR which removes the
member HDU entry from the grouping table and deletes the member HDU itself.

92 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
int fits—remove—member / ffgmrm
(fitsfile *fptr, long member, int rmopt, ? int *status)
7.10 Row Selection and Calculator Routines
These routines all parse and evaluate an input string containing a user defined arithmetic expression.
The first 3 routines select rows in a FITS table, based on whether the expression evaluates to true
(not equal to zero) or false (zero). The other routines evaluate the expression and calculate a value
for each row of the table. The allowed expression syntax is described in the row filter section in
the earlier `Extended File Name Syntax' chapter of this document.
1 Evaluate a boolean expression over the indicated rows, returning an array of flags indicating
which rows evaluated to TRUE/FALSE
int fits—find—rows / fffrow
(fitsfile *fptr, char *expr, long firstrow, long nrows,
? long *n—good—rows, char *row—status, int *status)
2 Find the first row which satisfies the input boolean expression
int fits—find—first—row / ffffrw
(fitsfile *fptr, char *expr, ? long *rownum, int *status)
3 Evaluate an expression on all rows of a table. If the input and output files are not the same,
copy the TRUE rows to the output file. If the files are the same, delete the FALSE rows
(preserve the TRUE rows).
int fits—select—rows / ffsrow
(fitsfile *infptr, fitsfile *outfptr, char *expr, ? int *status )
4 Calculate an expression for the indicated rows of a table, returning the results, cast as datatype
(TSHORT, TDOUBLE, etc), in array. If nulval==NULL, UNDEFs will be zeroed out. For
vector results, the number of elements returned may be less than nelements if nelements is
not an even multiple of the result dimension. Call fits test expr to obtain the dimensions of
the results.
int fits—calc—rows / ffcrow
(fitsfile *fptr, int datatype, char *expr, long firstrow,
long nelements, void *nulval, ? void *array, int *anynul, int *status)
5 Evaluate an expression and write the result either to a column (if the expression is a function
of other columns in the table) or to a keyword (if the expression evaluates to a constant and

7.11. FILE CHECKSUM ROUTINES 93
is not a function of other columns in the table). In the former case, the parName parameter
is the name of the column (which may or may not already exist) into which to write the
results, and parInfo contains an optional TFORM keyword value if a new column is being
created. If a TFORM value is not specified then a default format will be used, depending
on the expression. If the expression evalutes to a constant, then the result will be written to
the keyword name given by the parName parameter, and the parInfo parameter may be used
to supply an optional comment for the keyword. If the keyword does not already exist, then
the name of the keyword must be preceeded with a '#' character, otherwise the result will
be written to a column with that name.
int fits—calculator / ffcalc
(fitsfile *infptr, char *expr, fitsfile *outfptr, char *parName,
char *parInfo, ? int *status)
6 This calculator routine is similar to the previous routine, except that the expression is only
evaluated over the specified row ranges. nranges specifies the number of row ranges, and
firstrow and lastrow give the starting and ending row number of each range.
int fits—calculator—rng / ffcalc—rng
(fitsfile *infptr, char *expr, fitsfile *outfptr, char *parName,
char *parInfo, int nranges, long *firstrow, long *lastrow
? int *status)
7 Evaluate the given expression and return information on the result.
int fits—test—expr / fftexp
(fitsfile *fptr, char *expr, ? int *datatype, long *nelem, int *naxis,
long *naxes, int *status)
7.11 File Checksum Routines
The following routines either compute or validate the checksums for the CHDU. The DATASUM
keyword is used to store the numerical value of the 32­bit, 1's complement checksum for the data
unit alone. If there is no data unit then the value is set to zero. The numerical value is stored as an
ASCII string of digits, enclosed in quotes, because the value may be too large to represent as a 32­bit
signed integer. The CHECKSUM keyword is used to store the ASCII encoded COMPLEMENT of
the checksum for the entire HDU. Storing the complement, rather than the actual checksum, forces
the checksum for the whole HDU to equal zero. If the file has been modified since the checksums
were computed, then the HDU checksum will usually not equal zero. These checksum keyword
conventions are based on a paper by Rob Seaman published in the proceedings of the ADASS IV
conference in Baltimore in November 1994 and a later revision in June 1995.

94 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
1 Compute and write the DATASUM and CHECKSUM keyword values for the CHDU into the
current header. If the keywords already exist, their values will be updated only if necessary
(i.e., if the file has been modified since the original keyword values were computed).
int fits—write—chksum / ffpcks
(fitsfile *fptr, ? int *status)
2 Update the CHECKSUM keyword value in the CHDU, assuming that the DATASUM keyword
exists and already has the correct value. This routine calculates the new checksum for the
current header unit, adds it to the data unit checksum, encodes the value into an ASCII
string, and writes the string to the CHECKSUM keyword.
int fits—update—chksum / ffupck
(fitsfile *fptr, ? int *status)
3 Verify the CHDU by computing the checksums and comparing them with the keywords. The
data unit is verified correctly if the computed checksum equals the value of the DATASUM
keyword. The checksum for the entire HDU (header plus data unit) is correct if it equals
zero. The output DATAOK and HDUOK parameters in this routine are integers which will
have a value = 1 if the data or HDU is verified correctly, a value = 0 if the DATASUM or
CHECKSUM keyword is not present, or value = ­1 if the computed checksum is not correct.
int fits—verify—chksum / ffvcks
(fitsfile *fptr, ? int *dataok, int *hduok, int *status)
4 Compute and return the checksum values for the CHDU without creating or modifying the
CHECKSUM and DATASUM keywords. This routine is used internally by ffvcks, but may
be useful in other situations as well.
int fits—get—chksum/ /ffgcks
(fitsfile *fptr, ? unsigned long *datasum, unsigned long *hdusum,
int *status)
5 Encode a checksum value into a 16­character string. If complm is non­zero (true) then the 32­bit
sum value will be complemented before encoding.
int fits—encode—chksum / ffesum
(unsigned long sum, int complm, ? char *ascii);
6 Decode a 16­character checksum string into a unsigned long value. If is non­zero (true). then the
32­bit sum value will be complemented after decoding. The checksum value is also returned
as the value of the function.
unsigned long fits—decode—chksum / ffdsum
(char *ascii, int complm, ? unsigned long *sum);

7.12. DATE AND TIME UTILITY ROUTINES 95
7.12 Date and Time Utility Routines
The following routines help to construct or parse the FITS date/time strings. Starting in the year
2000, the FITS DATE keyword values (and the values of other `DATE­' keywords) must have the
form 'YYYY­MM­DD' (date only) or 'YYYY­MM­DDThh:mm:ss.ddd...' (date and time) where
the number of decimal places in the seconds value is optional. These times are in UTC. The older
'dd/mm/yy' date format may not be used for dates after 01 January 2000.
1 Get the current system date. C already provides standard library routines for getting the current
date and time, but this routine is provided for compatibility with the Fortran FITSIO library.
The returned year has 4 digits (1999, 2000, etc.)
int fits—get—system—date/ffgsdt
( ? int *day, int *month, int *year, int *status )
2 Get the current system date and time string ('YYYY­MM­DDThh:mm:ss'). The time will be
in UTC/GMT if available, as indicated by a returned timeref value = 0. If the returned value
of timeref = 1 then this indicates that it was not possible to convert the local time to UTC,
and thus the local time was returned.
int fits—get—system—time/ffgstm
(? char *datestr, int *timeref, int *status)
3 Construct a date string from the input date values. If the year is between 1900 and 1998, inclu­
sive, then the returned date string will have the old FITS format ('dd/mm/yy'), otherwise
the date string will have the new FITS format ('YYYY­MM­DD'). Use fits time2str instead
to always return a date string using the new FITS format.
int fits—date2str/ffdt2s
(int year, int month, int day, ? char *datestr, int *status)
4 Construct a new­format date + time string ('YYYY­MM­DDThh:mm:ss.ddd...'). If the year,
month, and day values all = 0 then only the time is encoded with format 'hh:mm:ss.ddd...'.
The decimals parameter specifies how many decimal places of fractional seconds to include
in the string. If `decimals' is negative, then only the date will be return ('YYYY­MM­DD').
int fits—time2str/fftm2s
(int year, int month, int day, int hour, int minute, double second,
int decimals, ? char *datestr, int *status)
5 Return the date as read from the input string, where the string may be in either the old
('dd/mm/yy') or new ('YYYY­MM­DDThh:mm:ss' or 'YYYY­MM­DD') FITS format. Null
pointers may be supplied for any unwanted output date parameters.

96 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
int fits—str2date/ffs2dt
(char *datestr, ? int *year, int *month, int *day, int *status)
6 Return the date and time as read from the input string, where the string may be in either the
old or new FITS format. The returned hours, minutes, and seconds values will be set to zero
if the input string does not include the time ('dd/mm/yy' or 'YYYY­MM­DD') . Similarly,
the returned year, month, and date values will be set to zero if the date is not included in
the input string ('hh:mm:ss.ddd...'). Null pointers may be supplied for any unwanted output
date and time parameters.
int fits—str2time/ffs2tm
(char *datestr, ? int *year, int *month, int *day, int *hour,
int *minute, double *second, int *status)
7.13 General Utility Routines
The following utility routines may be useful for certain applications:
1 Convert a character string to uppercase (operates in place).
void fits—uppercase / ffupch (char *string)
2 Compare the input template string against the reference string to see if they match. The
template string may contain wildcard characters: '*' will match any sequence of characters
(including zero characters) and '%' will match any single character in the reference string. If
casesen = CASESEN = TRUE then the match will be case sensitive, otherwise the case of the
letters will be ignored if casesen = CASEINSEN = FALSE. The returned MATCH parameter
will be TRUE if the 2 strings match, and EXACT will be TRUE if the match is exact (i.e.,
if no wildcard characters were used in the match). Both strings must be 68 characters or less
in length.
void fits—compare—str / ffcmps
(char *templt, char *string, int casesen, ? int *match, int *exact)
3 Test that the keyword name contains only legal characters: A­Z,0­9, hyphen, and underscore.
int fits—test—keyword / fftkey (char *keyname, ? int *status)
4 Test that the keyword record contains only legal printable ASCII characters
int fits—test—record / fftrec (char *card, ? int *status)

7.13. GENERAL UTILITY ROUTINES 97
5 Test whether the current header contains any NULL (ASCII 0) characters. These characters are
illegal in the header, but they will go undetected by most of the CFITSIO keyword header
routines, because the null is interpreted as the normal end­of­string terminator. This routine
returns the position of the first null character in the header, or zero if there are no nulls. For
example a returned value of 110 would indicate that the first NULL is located in the 30th
character of the second keyword in the header (recall that each header record is 80 characters
long). Note that this is one of the few CFITSIO routines in which the returned value is not
necessarily equal to the status value).
int fits—null—check / ffnchk (char *card, ? int *status)
6 Parse a header keyword record and return the name of the keyword, and the length of the name.
The keyword name normally occupies the first 8 characters of the record, except under the
HIERARCH convention where the name can be up to 70 characters in length.
int fits—get—keyname / ffgknm
(char *card, ? char *keyname, int *keylength, int *status)
7 Parse a header keyword record, returning the value (as a literal character string) and comment
strings. If the keyword has no value (columns 9­10 not equal to '= '), then a null value string
is returned and the comment string is set equal to column 9 ­ 80 of the input string.
int fits—parse—value / ffpsvc
(char *card, ? char *value, char *comment, int *status)
8 Construct an array indexed keyword name (ROOT + nnn). This routine appends the sequence
number to the root string to create a keyword name (e.g., 'NAXIS' + 2 = 'NAXIS2')
int fits—make—keyn / ffkeyn
(char *keyroot, int value, ? char *keyname, int *status)
9 Construct a sequence keyword name (n + ROOT). This routine concatenates the sequence
number to the front of the root string to create a keyword name (e.g., 1 + 'CTYP' = '1CTYP')
int fits—make—nkey / ffnkey
(int value, char *keyroot, ? char *keyname, int *status)
10 Determine the datatype of a keyword value string. This routine parses the keyword value string
to determine its datatype. Returns 'C', 'L', 'I', 'F' or 'X', for character string, logical, integer,
floating point, or complex, respectively.
int fits—get—keytype / ffdtyp
(char *value, ? char *dtype, int *status)

98 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
11 Return the class of input header record. The record is classified into one of the following
catagories (the class values are defined in fitsio.h). Note that this is one of the few CFITSIO
routines that does not return a status value.
Class Value Keywords
TYP—STRUC—KEY 10 SIMPLE, BITPIX, NAXIS, NAXISn, EXTEND, BLOCKED,
GROUPS, PCOUNT, GCOUNT, END
XTENSION, TFIELDS, TTYPEn, TBCOLn, TFORMn, THEAP,
and the first 4 COMMENT keywords in the primary array
that define the FITS format.
TYP—CMPRS—KEY 20 The experimental keywords used in the compressed
image format ZIMAGE, ZCMPTYPE, ZNAMEn, ZVALn,
ZTILEn, ZBITPIX, ZNAXISn, ZSCALE, ZZERO, ZBLANK
TYP—SCAL—KEY 30 BSCALE, BZERO, TSCALn, TZEROn
TYP—NULL—KEY 40 BLANK, TNULLn
TYP—DIM—KEY 50 TDIMn
TYP—RANG—KEY 60 TLMINn, TLMAXn, TDMINn, TDMAXn, DATAMIN, DATAMAX
TYP—UNIT—KEY 70 BUNIT, TUNITn
TYP—DISP—KEY 80 TDISPn
TYP—HDUID—KEY 90 EXTNAME, EXTVER, EXTLEVEL, HDUNAME, HDUVER, HDULEVEL
TYP—CKSUM—KEY 100 CHECKSUM, DATASUM
TYP—WCS—KEY 110 CTYPEn, CUNITn, CRVALn, CRPIXn, CROTAn, CDELTn
CDj—is, PVj—ms, LONPOLEs, LATPOLEs
TCTYPn, TCTYns, TCUNIn, TCUNns, TCRVLn, TCRVns, TCRPXn,
TCRPks, TCDn—k, TCn—ks, TPVn—m, TPn—ms, TCDLTn, TCROTn
jCTYPn, jCTYns, jCUNIn, jCUNns, jCRVLn, jCRVns, iCRPXn,
iCRPns, jiCDn, jiCDns, jPVn—m, jPn—ms, jCDLTn, jCROTn
(i,j,m,n are integers, s is any letter)
TYP—REFSYS—KEY 120 EQUINOXs, EPOCH, MJD­OBSs, RADECSYS, RADESYSs
TYP—COMM—KEY 130 COMMENT, HISTORY, (blank keyword)
TYP—CONT—KEY 140 CONTINUE
TYP—USER—KEY 150 all other keywords
int fits—get—keyclass / ffgkcl (char *card)
12 Parse the 'TFORM' binary table column format string. This routine parses the input TFORM
character string and returns the integer datatype code, the repeat count of the field, and, in
the case of character string fields, the length of the unit string. See Chapter 9 for the allowed
values for the returned typecode parameter. A null pointer may be given for any output
parameters that are not needed.
int fits—binary—tform / ffbnfm
(char *tform, ? int *typecode, long *repeat, long *width,
int *status)

7.13. GENERAL UTILITY ROUTINES 99
13 Parse the 'TFORM' keyword value that defines the column format in an ASCII table. This
routine parses the input TFORM character string and returns the datatype code, the width
of the column, and (if it is a floating point column) the number of decimal places to the right
of the decimal point. The returned datatype codes are the same as for the binary table, with
the following additional rules: integer columns that are between 1 and 4 characters wide are
defined to be short integers (code = TSHORT). Wider integer columns are defined to be
regular integers (code = TLONG). Similarly, Fixed decimal point columns (with TFORM
= 'Fw.d') are defined to be single precision reals (code = TFLOAT) if w is between 1 and
7 characters wide, inclusive. Wider 'F' columns will return a double precision data code
(= TDOUBLE). 'Ew.d' format columns will have datacode = TFLOAT, and 'Dw.d' format
columns will have datacode = TDOUBLE. A null pointer may be given for any output
parameters that are not needed.
int fits—ascii—tform / ffasfm
(char *tform, ? int *typecode, long *width, int *decimals,
int *status)
14 Calculate the starting column positions and total ASCII table width based on the input array
of ASCII table TFORM values. The SPACE input parameter defines how many blank spaces
to leave between each column (it is recommended to have one space between columns for
better human readability).
int fits—get—tbcol / ffgabc
(int tfields, char **tform, int space, ? long *rowlen,
long *tbcol, int *status)
15 Parse a template header record and return a formatted 80­character string suitable for append­
ing to (or deleting from) a FITS header file. This routine is useful for parsing lines from
an ASCII template file and reformatting them into legal FITS header records. The format­
ted string may then be passed to the fits write record, ffmcrd, or fits delete key routines to
append or modify a FITS header record.
int fits—parse—template / ffgthd
(char *templt, ? char *card, int *keytype, int *status)
The input templt character string generally should contain 3 tokens: (1) the KEYNAME, (2) the
VALUE, and (3) the COMMENT string. The TEMPLATE string must adhere to the following
format:
­ The KEYNAME token must begin in columns 1­8 and be a maximum of 8 characters long. A
legal FITS keyword name may only contain the characters A­Z, 0­9, and '­' (minus sign) and
underscore. This routine will automatically convert any lowercase characters to uppercase in
the output string. If the first 8 characters of the template line are blank then the remainder
of the line is considered to be a FITS comment (with a blank keyword name).

100 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
­ The VALUE token must be separated from the KEYNAME token by one or more spaces and/or
an '=' character. The datatype of the VALUE token (numeric, logical, or character string) is
automatically determined and the output CARD string is formatted accordingly. The value
token may be forced to be interpreted as a string (e.g. if it is a string of numeric digits) by
enclosing it in single quotes.
­ The COMMENT token is optional, but if present must be separated from the VALUE token by
at least one blank space and a '/' character.
­ One exception to the above rules is that if the first non­blank character in the first 8 characters
of the template string is a minus sign ('­') followed by a single token, or a single token followed
by an equal sign, then it is interpreted as the name of a keyword which is to be deleted from
the FITS header.
­ The second exception is that if the template string starts with a minus sign and is followed by
2 tokens (without an equals sign between them) then the second token is interpreted as the
new name for the keyword specified by first token. In this case the old keyword name (first
token) is returned in characters 1­8 of the returned CARD string, and the new keyword name
(the second token) is returned in characters 41­48 of the returned CARD string. These old
and new names may then be passed to the ffmnam routine which will change the keyword
name.
The keytype output parameter indicates how the returned CARD string should be interpreted:
keytype interpretation
­­­­­­­ ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
­2 Rename the keyword with name = the first 8 characters of CARD
to the new name given in characters 41 ­ 48 of CARD.
­1 delete the keyword with this name from the FITS header.
0 append the CARD string to the FITS header if the
keyword does not already exist, otherwise update
the keyword value and/or comment field if is already exists.
1 This is a HISTORY or COMMENT keyword; append it to the header
2 END record; do not explicitly write it to the FITS file.
EXAMPLES: The following lines illustrate valid input template strings:
INTVAL 7 / This is an integer keyword
RVAL 34.6 / This is a floating point keyword

7.13. GENERAL UTILITY ROUTINES 101
EVAL=­12.45E­03 / This is a floating point keyword in exponential notation
lval F / This is a boolean keyword
This is a comment keyword with a blank keyword name
SVAL1 = 'Hello world' / this is a string keyword
SVAL2 '123.5' this is also a string keyword
sval3 123+ / this is also a string keyword with the value '123+ '
# the following template line deletes the DATE keyword
­ DATE
# the following template line modifies the NAME keyword to OBJECT
­ NAME OBJECT
16 Check that the Header fill bytes (if any) are all blank. These are the bytes that may follow
END keyword and before the beginning of data unit, or the end of the HDU if there is no
data unit.
int ffchfl(fitsfile *fptr, ? int *status)
17 Check that the Data fill bytes (if any) are all zero (for IMAGE or BINARY Table HDU) or all
blanks (for ASCII table HDU). These file bytes may be located after the last valid data byte
in the HDU and before the physcal end of the HDU.
int ffcdfl(fitsfile *fptr, ? int *status)

102 CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES

Chapter 8
Specialized CFITSIO Interface
Routines
The basic interface routines described in the previous chapter should be used whenever possible,
but the routines described in this chapter are also available if necessary. Some of these routines
perform more specialized function that cannot easily be done with the basic interface routines while
others duplicate the functionality of the basic routines but have a slightly different calling sequence.
8.1 Specialized FITS File Access Routines
1 Open a FITS file residing in core computer memory. This routine analogous to fits open file.
In general, the application must preallocate an initial block of memory to hold the FITS
file: 'buffptr' points to the starting address and 'buffsize' gives the initial size of the block
of memory. 'mem realloc' is a pointer to an optional function that CFITSIO can call to
allocate additional memory, if needed, and is modeled after the standard C 'realloc' function;
a null pointer may be given if the initial allocation of memory is all that will be required.
The 'deltasize' parameter may be used to suggest a minimum amount of additional memory
that should be allocated during each call to the memory reallocation function. By default,
CFITSIO will reallocate enough additional space to hold the entire currently defined FITS
file (as given by the NAXISn keywords) or 1 FITS block (= 2880 bytes), which ever is larger.
Values of deltasize less than 2880 will be ignored. Since the memory reallocation operation can
be computationally expensive, allocating a larger initial block of memory, and/or specifying
a larger delta size value may help to reduce the number of reallocation calls and make the
application program run faster.
int fits—open—memory / ffomem
(fitsfile **fptr, const char *name, int mode, void **buffptr,
size—t *buffsize, size—t deltasize,
void *(*mem—realloc)(void *p, size—t newsize), int *status)
103

104 CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES
2 Flush any internal buffers of data to the output FITS file. This routine rarely needs to be
called, but can be useful when writing to the FITS files in memory, and will ensure that if
the program subsequently aborts then the FITS file will have been closed properly.
int fits—flush—file / ffflus
(fitsfile *fptr, ? int *status)
8.2 Specialized HDU Access Routines
1 Get the byte offsets in the FITS file to the start of the header and the start and end of the
data in the CHDU. The difference between headstart and dataend is the size of the CHDU.
If the CHDU is the last HDU in the file, then dataend is also equal to the size of the entire
FITS file. Null pointers may be input for any of the address parameters if their values are
not needed.
int fits—get—hduaddr / ffghad
(fitsfile *fptr, ? long *headstart, long *datastart, long *dataend,
int *status)
2 Create (append) a new empty HDU at the end of the FITS file. This is now the CHDU but it
is completely empty and has no header keywords. It is recommended that fits create img or
fits create tbl be used instead of this routine.
int fits—create—hdu / ffcrhd
(fitsfile *fptr, ? int *status)
3 Insert a new IMAGE extension immediately following the CHDU. Any following extensions
will be shifted down to make room for the new extension. If there are no other following
extensions then the new image extension will simply be appended to the end of the file. The
new extension will become the CHDU. Refer to Chapter 9 for a list of pre­defined bitpix
values.
int fits—insert—img / ffiimg
(fitsfile *fptr, int bitpix, int naxis, long *naxes, ? int *status)
4 Insert a new ASCII or binary table extension immediately following the CHDU. Any following
extensions will be shifted down to make room for the new extension. If there are no other
following extensions then the new table extension will simply be appended to the end of the
file. If the FITS file is currently empty then this routine will create a dummy primary array
before appending the table to it. The new extension will become the CHDU. The tunit and
extname parameters are optional and a null pointer may be given if they are not defined.
When inserting an ASCII table with fits insert atbl, a null pointer may given for the *tbcol

8.2. SPECIALIZED HDU ACCESS ROUTINES 105
parameter in which case each column of the table will be separated by a single space character.
Similarly, if the input value of rowlen is 0, then CFITSIO will calculate the default rowlength
based on the tbcol and ttype values. When inserting a binary table with fits insert btbl,
if there are following extensions in the file and if the table contains variable length array
columns then pcount must specify the expected final size of the data heap, otherwise pcount
must = 0.
int fits—insert—atbl / ffitab
(fitsfile *fptr, long rowlen, long nrows, int tfields, char *ttype[],
long *tbcol, char *tform[], char *tunit[], char *extname, ? int *status)
int fits—insert—btbl / ffibin
(fitsfile *fptr, long nrows, int tfields, char **ttype,
char **tform, char **tunit, char *extname, long pcount, ? int *status)
5 Modify the size, dimensions, and/or datatype of the current primary array or image extension.
If the new image, as specified by the input arguments, is larger than the current existing
image in the FITS file then zero fill data will be inserted at the end of the current image and
any following extensions will be moved further back in the file. Similarly, if the new image
is smaller than the current image then any following extensions will be shifted up towards
the beginning of the FITS file and the image data will be truncated to the new size. This
routine rewrites the BITPIX, NAXIS, and NAXISn keywords with the appropriate values for
the new image.
int fits—resize—img / ffrsim
(fitsfile *fptr, int bitpix, int naxis, long *naxes, ? int *status)
6 Copy the header (and not the data) from the CHDU associated with infptr to the CHDU asso­
ciated with outfptr. If the current output HDU is not completely empty, then the CHDU will
be closed and a new HDU will be appended to the output file. This routine will automatically
transform the necessary keywords when copying a primary array to and image extension, or
an image extension to a primary array. An empty output data unit will be created (all values
= 0).
int fits—copy—header / ffcphd
(fitsfile *infptr, fitsfile *outfptr, ? int *status)
7 Copy the data (and not the header) from the CHDU associated with infptr to the CHDU
associated with outfptr. This will overwrite any data previously in the output CHDU. This
low level routine is used by fits copy hdu, but it may also be useful in certain application
programs that want to copy the data from one FITS file to another but also want to modify
the header keywords. The required FITS header keywords which define the structure of the
HDU must be written to the output CHDU before calling this routine.

106 CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES
int fits—copy—data / ffcpdt
(fitsfile *infptr, fitsfile *outfptr, ? int *status)
8 This routine forces CFITSIO to rescan the current header keywords that define the structure
of the HDU (such as the NAXIS and BITPIX keywords) so that it reinitializes the internal
buffers that describe the HDU structure. This routine is useful for reinitializing the structure
of an HDU if any of the required keywords (e.g., NAXISn) have been modified. In practice
it should rarely be necessary to call this routine because CFITSIO internally calls it in most
situations.
int fits—set—hdustruc / ffrdef
(fitsfile *fptr, ? int *status) (DEPRECATED)
8.3 Specialized Header Keyword Routines
8.3.1 Header Information Routines
1 Reserve space in the CHU for MOREKEYS more header keywords. This routine may be called
to allocate space for additional keywords at the time the header is created (prior to writing
any data). CFITSIO can dynamically add more space to the header when needed, however
it is more efficient to preallocate the required space if the size is known in advance.
int fits—set—hdrsize / ffhdef
(fitsfile *fptr, int morekeys, ? int *status)
2 Return the number of keywords in the header (not counting the END keyword) and the current
position in the header. The position is the number of the keyword record that will be read
next (or one greater than the position of the last keyword that was read). A value of 1 is
returned if the pointer is positioned at the beginning of the header.
int fits—get—hdrpos / ffghps
(fitsfile *fptr, ? int *keysexist, int *keynum, int *status)
8.3.2 Read and Write the Required Keywords
1 Write the primary header or IMAGE extension keywords into the CHU. The simpler fits write imghdr
routine is equivalent to calling fits write grphdr with the default values of simple = TRUE,
pcount = 0, gcount = 1, and extend = TRUE. The PCOUNT, GCOUNT and EXTEND
keywords are not required in the primary header and are only written if pcount is not equal
to zero, gcount is not equal to zero or one, and if extend is TRUE, respectively. When writing
to an IMAGE extension, the SIMPLE and EXTEND parameters are ignored. It is recom­
mended that fits create image or fits create tbl be used instead of these routines to write the
required header keywords.

8.3. SPECIALIZED HEADER KEYWORD ROUTINES 107
int fits—write—imghdr / ffphps
(fitsfile *fptr, int bitpix, int naxis, long *naxes, ? int *status)
int fits—write—grphdr / ffphpr
(fitsfile *fptr, int simple, int bitpix, int naxis, long *naxes,
long pcount, long gcount, int extend, ? int *status)
2 Write the ASCII table header keywords into the CHU. The optional TUNITn and EXTNAME
keywords are written only if the input pointers are not null. A null pointer may given for the
*tbcol parameter in which case a single space will be inserted between each column of the
table. Similarly, if rowlen is given = 0, then CFITSIO will calculate the default rowlength
based on the tbcol and ttype values.
int fits—write—atblhdr / ffphtb
(fitsfile *fptr, long rowlen, long nrows, int tfields, char **ttype,
long *tbcol, char **tform, char **tunit, char *extname, ? int *status)
3 Write the binary table header keywords into the CHU. The optional TUNITn and EXTNAME
keywords are written only if the input pointers are not null. The pcount parameter, which
specifies the size of the variable length array heap, should initially = 0; CFITSIO will au­
tomatically update the PCOUNT keyword value if any variable length array data is written
to the heap. The TFORM keyword value for variable length vector columns should have the
form 'Pt(len)' or '1Pt(len)' where `t' is the data type code letter (A,I,J,E,D, etc.) and `len' is
an integer specifying the maximum length of the vectors in that column (len must be greater
than or equal to the longest vector in the column). If `len' is not specified when the table
is created (e.g., the input TFORMn value is just '1Pt') then CFITSIO will scan the column
when the table is first closed and will append the maximum length to the TFORM keyword
value. Note that if the table is subsequently modified to increase the maximum length of the
vectors then the modifying program is responsible for also updating the TFORM keyword
value.
int fits—write—btblhdr / ffphbn
(fitsfile *fptr, long nrows, int tfields, char **ttype,
char **tform, char **tunit, char *extname, long pcount, ? int *status)
4 Read the primary header or IMAGE extension keywords in the CHU. When reading from an
IMAGE extension the SIMPLE and EXTEND parameters are ignored. A null pointer may
be supplied for any of the returned parameters that are not needed.
int fits—read—imghdr / ffghpr
(fitsfile *fptr, int maxdim, ? int *simple, int *bitpix, int *naxis,
long *naxes, long *pcount, long *gcount, int *extend, int *status)
5 Read the ASCII table header keywords in the CHU. A null pointer may be supplied for any of
the returned parameters that are not needed.

108 CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES
int fits—read—atblhdr / ffghtb
(fitsfile *fptr,int maxdim, ? long *rowlen, long *nrows,
int *tfields, char **ttype, long *tbcol, char **tform, char **tunit,
char *extname, int *status)
6 Read the binary table header keywords from the CHU. A null pointer may be supplied for any
of the returned parameters that are not needed.
int fits—read—btblhdr / ffghbn
(fitsfile *fptr, int maxdim, ? long *nrows, int *tfields,
char **ttype, char **tform, char **tunit, char *extname,
long *pcount, int *status)
8.3.3 Specialized Write Keyword Routines
These routines simply append a new keyword to the header and do not check to see if a keyword
with the same name already exists. In general it is preferable to use the fits update key routine to
ensure that the same keyword is not written more than once to the header.
1 Write (append) a new keyword with an undefined, or null, value into the CHU. The value string
of the keyword is left blank in this case. A null pointer may be entered for the comment
parameter.
int fits—write—key—null / ffpkyu
(fitsfile *fptr, char *keyname, char *comment, ? int *status)
2 Write (append) a new keyword of the appropriate datatype into the CHU. A null pointer may
be entered for the comment parameter, which will cause the comment field of the keyword to
be left blank.
int fits—write—key—str / ffpkys
(fitsfile *fptr, char *keyname, char *value, char *comment,
? int *status)
int fits—write—key—[log, lng] / ffpky[lj]
(fitsfile *fptr, char *keyname, DTYPE numval, char *comment,
? int *status)
int fits—write—key—[flt, dbl, fixflg, fixdbl] / ffpky[edfg]
(fitsfile *fptr, char *keyname, DTYPE numval, int decimals,
char *comment, ? int *status)
int fits—write—key—[cmp, dblcmp, fixcmp, fixdblcmp] / ffpk[yc,ym,fc,fm]
(fitsfile *fptr, char *keyname, DTYPE *numval, int decimals,
char *comment, ? int *status)

8.3. SPECIALIZED HEADER KEYWORD ROUTINES 109
3 Write (append) a string valued keyword into the CHU which may be longer than 68 characters
in length. This uses the Long String Keyword convention that is described in the`Local
FITS Conventions' section in Chapter 4. Since this uses a non­standard FITS convention
to encode the long keyword string, programs which use this routine should also call the
fits write key longwarn routine to add some COMMENT keywords to warn users of the FITS
file that this convention is being used. The fits write key longwarn routine also writes a
keyword called LONGSTRN to record the version of the longstring convention that has been
used, in case a new convention is adopted at some point in the future. If the LONGSTRN
keyword is already present in the header, then fits write key longwarn will simply return
without doing anything.
int fits—write—key—longstr / ffpkls
(fitsfile *fptr, char *keyname, char *longstr, char *comment,
? int *status)
int fits—write—key—longwarn / ffplsw
(fitsfile *fptr, ? int *status)
4 Write (append) a numbered sequence of keywords into the CHU. The starting index number
(nstart) must be greater than 0. One may append the same comment to every keyword (and
eliminate the need to have an array of identical comment strings, one for each keyword) by
including the ampersand character as the last non­blank character in the (first) COMMENTS
string parameter. This same string will then be used for the comment field in all the keywords.
One may also enter a null pointer for the comment parameter to leave the comment field of
the keyword blank.
int fits—write—keys—str / ffpkns
(fitsfile *fptr, char *keyroot, int nstart, int nkeys,
char **value, char **comment, ? int *status)
int fits—write—keys—[log, lng] / ffpkn[lj]
(fitsfile *fptr, char *keyroot, int nstart, int nkeys,
DTYPE *numval, char **comment, int *status)
int fits—write—keys—[flt, dbl, fixflg, fixdbl] / ffpkne[edfg]
(fitsfile *fptr, char *keyroot, int nstart, int nkey,
DTYPE *numval, int decimals, char **comment, ? int *status)
5 Copy an indexed keyword from one HDU to another, modifying the index number of the keyword
name in the process. For example, this routine could read the TLMIN3 keyword from the
input HDU (by giving keyroot = ''TLMIN'' and innum = 3) and write it to the output HDU
with the keyword name TLMIN4 (by setting outnum = 4). If the input keyword does not
exist, then this routine simply returns without indicating an error.

110 CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES
int fits—copy—key / ffcpky
(fitsfile *infptr, fitsfile *outfptr, int innum, int outnum,
char *keyroot, ? int *status)
6 Write (append) a `triple precision' keyword into the CHU in F28.16 format. The floating point
keyword value is constructed by concatenating the input integer value with the input double
precision fraction value (which must have a value between 0.0 and 1.0). The ffgkyt routine
should be used to read this keyword value, because the other keyword reading routines will
not preserve the full precision of the value.
int fits—write—key—triple / ffpkyt
(fitsfile *fptr, char *keyname, long intval, double frac,
char *comment, ? int *status)
7 Write keywords to the CHDU that are defined in an ASCII template file. The format of the
template file is described under the fits parse template routine below.
int fits—write—key—template / ffpktp
(fitsfile *fptr, const char *filename, ? int *status)
8.3.4 Insert Keyword Routines
These insert routines are somewhat less efficient than the `update' or `write' keyword routines
because the following keywords in the header must be shifted down to make room for the inserted
keyword.
1 Insert a new keyword record into the CHU at the specified position (i.e., immediately preceding
the (keynum)th keyword in the header.)
int fits—insert—record / ffirec
(fitsfile *fptr, int keynum, char *card, ? int *status)
2 Insert a new keyword into the CHU. The new keyword is inserted immediately following the last
keyword that has been read from the header. The `longstr' version has the same functionality
as the `str' version except that it also supports the local long string keyword convention for
strings longer than 68 characters. A null pointer may be entered for the comment parameter
which will cause the comment field to be left blank.
int fits—insert—key—[str, longstr] / ffi[kys, kls]
(fitsfile *fptr, char *keyname, char *value, char *comment,
? int *status)
int fits—insert—key—[log, lng] / ffiky[lj]

8.3. SPECIALIZED HEADER KEYWORD ROUTINES 111
(fitsfile *fptr, char *keyname, DTYPE numval, char *comment,
? int *status)
int fits—insert—key—[flt, fixflt, dbl, fixdbl] / ffiky[edfg]
(fitsfile *fptr, char *keyname, DTYPE numval, int decimals,
char *comment, ? int *status)
int fits—insert—key—[cmp, dblcmp, fixcmp, fixdblcmp] / ffik[yc,ym,fc,fm]
(fitsfile *fptr, char *keyname, DTYPE *numval, int decimals,
char *comment, ? int *status)
3 Insert a new keyword with an undefined, or null, value into the CHU. The value string of the
keyword is left blank in this case.
int fits—insert—key—null / ffikyu
(fitsfile *fptr, char *keyname, char *comment, ? int *status)
8.3.5 Specialized Read Keyword Routines
Wild card characters may be used when specifying the name of the keyword to be read.
1 Read the name, value (as a string), and comment of the nth keyword in CHU. If a NULL
comment pointer is given on input, then the comment string will not be returned. A null
value string will be returned if the keyword has no defined value (i.e., if the value field in the
keyword is blank).
int fits—read—keyn / ffgkyn
(fitsfile *fptr, int keynum, ? char *keyname, char *value,
char *comment, int *status)
2 Read the next keyword whose name matches one of the strings in 'inclist' but does not match any
of the strings in 'exclist'. The strings in inclist and exclist may contain wild card characters
(*, ?, and #) as described at the beginning of this section. This routine searches from the
current header position to the end of the header, only, and does not continue the search from
the top of the header back to the original position. The current header position may be
reset with the ffgrec routine. Note that nexc may be set = 0 if there are no keywords to
be excluded. This routine returns status = KEY NO EXIST if a matching keyword is not
found.
int fits—find—nextkey / ffgnxk
(fitsfile *fptr, char **inclist, int ninc, char **exclist,
int nexc, ? char *card, int *status)

112 CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES
3 Read the literal keyword value as a character string. Regardless of the datatype of the keyword,
this routine simply returns the string of characters in the value field of the keyword along
with the comment field. If a NULL comment pointer is given on input, then the comment
string will not be returned.
int fits—read—keyword / ffgkey
(fitsfile *fptr, char *keyname, ? char *value, char *comment,
int *status)
4 Read a keyword value (with the appropriate datatype) and comment from the CHU. If a NULL
comment pointer is given on input, then the comment string will not be returned. If the
value of the keyword is not defined (i.e., the value field is blank) then an error status =
VALUE UNDEFINED will be returned and the input value will not be changed.
int fits—read—key—str / ffgkys
(fitsfile *fptr, char *keyname, ? char *value, char *comment,
int *status);
NOTE: after calling the following routine, programs must explicitly free
the memory allocated for 'longstr' after it is no longer needed.
int fits—read—key—longstr / ffgkls
(fitsfile *fptr, char *keyname, ? char **longstr, char *comment,
int *status)
int fits—read—key—[log, lng, flt, dbl, cmp, dblcmp] / ffgky[ljedcm]
(fitsfile *fptr, char *keyname, ? DTYPE *numval, char *comment,
int *status)
5 Read a sequence of indexed keyword values. The starting index number (nstart) must be greater
than 0. If the value of any of the keywords is not defined (i.e., the value field is blank) then an
error status = VALUE UNDEFINED will be returned and the input value for the undefined
keyword(s) will not be changed. These routines do not support wild card characters in the
root name.
int fits—read—keys—str / ffgkns
(fitsfile *fptr, char *keyname, int nstart, int nkeys,
? char **value, int *nfound, int *status)
int fits—read—keys—[log, lng, flt, dbl] / ffgkn[ljed]
(fitsfile *fptr, char *keyname, int nstart, int nkeys,
? DTYPE *numval, int *nfound, int *status)

8.3. SPECIALIZED HEADER KEYWORD ROUTINES 113
6 Read the value of a floating point keyword, returning the integer and fractional parts of the
value in separate routine arguments. This routine may be used to read any keyword but is
especially useful for reading the 'triple precision' keywords written by ffpkyt.
int fits—read—key—triple / ffgkyt
(fitsfile *fptr, char *keyname, ? long *intval, double *frac,
char *comment, int *status)
8.3.6 Modify Keyword Routines
These routines modify the value of an existing keyword. An error is returned if the keyword does
not exist. Wild card characters may be used when specifying the name of the keyword to be
modified.
1 Modify (overwrite) the nth 80­character header record in the CHU.
int fits—modify—record / ffmrec
(fitsfile *fptr, int keynum, char *card, ? int *status)
2 Modify (overwrite) the 80­character header record for the named keyword in the CHU. This
can be used to overwrite the name of the keyword as well as its value and comment fields.
int fits—modify—card / ffmcrd
(fitsfile *fptr, char *keyname, char *card, ? int *status)
5 Modify the value and comment fields of an existing keyword in the CHU. The `longstr' version
has the same functionality as the `str' version except that it also supports the local long
string keyword convention for strings longer than 68 characters. Optionally, one may modify
only the value field and leave the comment field unchanged by setting the input COMMENT
parameter equal to the ampersand character (&) or by entering a null pointer for the comment
parameter.
int fits—modify—key—[str, longstr] / ffm[kys, kls]
(fitsfile *fptr, char *keyname, char *value, char *comment,
? int *status);
int fits—modify—key—[log, lng] / ffmky[lj]
(fitsfile *fptr, char *keyname, DTYPE numval, char *comment,
? int *status)
int fits—modify—key—[flt, dbl, fixflt, fixdbl] / ffmky[edfg]
(fitsfile *fptr, char *keyname, DTYPE numval, int decimals,
char *comment, ? int *status)

114 CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES
int fits—modify—key—[cmp, dblcmp, fixcmp, fixdblcmp] / ffmk[yc,ym,fc,fm]
(fitsfile *fptr, char *keyname, DTYPE *numval, int decimals,
char *comment, ? int *status)
6 Modify the value of an existing keyword to be undefined, or null. The value string of the keyword
is set to blank. Optionally, one may leave the comment field unchanged by setting the input
COMMENT parameter equal to the ampersand character (&) or by entering a null pointer.
int fits—modify—key—null / ffmkyu
(fitsfile *fptr, char *keyname, char *comment, ? int *status)
8.3.7 Specialized Update Keyword Routines
1 These update routines modify the value, and optionally the comment field, of the keyword if it
already exists, otherwise the new keyword is appended to the header. A separate routine is
provided for each keyword datatype. The `longstr' version has the same functionality as the
`str' version except that it also supports the local long string keyword convention for strings
longer than 68 characters. A null pointer may be entered for the comment parameter which
will leave the comment field unchanged or blank.
int fits—update—key—[str, longstr] / ffu[kys, kls]
(fitsfile *fptr, char *keyname, char *value, char *comment,
? int *status)
int fits—update—key—[log, lng] / ffuky[lj]
(fitsfile *fptr, char *keyname, DTYPE numval, char *comment,
? int *status)
int fits—update—key—[flt, dbl, fixflt, fixdbl] / ffuky[edfg]
(fitsfile *fptr, char *keyname, DTYPE numval, int decimals,
char *comment, ? int *status)
int fits—update—key—[cmp, dblcmp, fixcmp, fixdblcmp] / ffuk[yc,ym,fc,fm]
(fitsfile *fptr, char *keyname, DTYPE *numval, int decimals,
char *comment, ? int *status)
8.4 Define Data Scaling and Undefined Pixel Parameters
These routines define or modify the internal parameters used by CFITSIO to either scale the data
or to represent undefined pixels. Generally CFITSIO will scale the data according to the values
of the BSCALE and BZERO (or TSCALn and TZEROn) keywords, however these routines may
be used to override the keyword values. This may be useful when one wants to read or write the

8.4. DEFINE DATA SCALING AND UNDEFINED PIXEL PARAMETERS 115
raw unscaled values in the FITS file. Similarly, CFITSIO generally uses the value of the BLANK
or TNULLn keyword to signify an undefined pixel, but these routines may be used to override this
value. These routines do not create or modify the corresponding header keyword values.
1 Reset the scaling factors in the primary array or image extension; does not change the BSCALE
and BZERO keyword values and only affects the automatic scaling performed when the data
elements are written/read to/from the FITS file. When reading from a FITS file the returned
data value = (the value given in the FITS array) * BSCALE + BZERO. The inverse formula
is used when writing data values to the FITS file.
int fits—set—bscale / ffpscl
(fitsfile *fptr, double scale, double zero, ? int *status)
2 Reset the scaling parameters for a table column; does not change the TSCALn or TZEROn
keyword values and only affects the automatic scaling performed when the data elements are
written/read to/from the FITS file. When reading from a FITS file the returned data value
= (the value given in the FITS array) * TSCAL + TZERO. The inverse formula is used when
writing data values to the FITS file.
int fits—set—tscale / fftscl
(fitsfile *fptr, int colnum, double scale, double zero,
? int *status)
3 Define the integer value to be used to signify undefined pixels in the primary array or image
extension. This is only used if BITPIX = 8, 16, or 32. This does not create or change the
value of the BLANK keyword in the header.
int fits—set—imgnul / ffpnul
(fitsfile *fptr, long nulval, ? int *status)
4 Define the string to be used to signify undefined pixels in a column in an ASCII table. This
does not create or change the value of the TNULLn keyword.
int fits—set—atblnull / ffsnul
(fitsfile *fptr, int colnum, char *nulstr, ? int *status)
5 Define the value to be used to signify undefined pixels in an integer column in a binary table
(where TFORMn = 'B', 'I', or 'J'). This does not create or change the value of the TNULLn
keyword.
int fits—set—btblnul / fftnul
(fitsfile *fptr, int colnum, long nulval, ? int *status)

116 CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES
8.5 Specialized FITS Primary Array or IMAGE Extension I/O
Routines
These routines read or write data values in the primary data array (i.e., the first HDU in the FITS
file) or an IMAGE extension. Automatic data type conversion is performed for if the data type
of the FITS array (as defined by the BITPIX keyword) differs from the data type of the array in
the calling routine. The data values are automatically scaled by the BSCALE and BZERO header
values as they are being written or read from the FITS array. Unlike the basic routines described in
the previous chapter, most of these routines specifically support the FITS random groups format.
The more primitive reading and writing routines (i. e., ffppr , ffppn , ffppn, ffgpv , or ffgpf ) simply
treat the primary array as a long 1­dimensional array of pixels, ignoring the intrinsic dimensionality
of the array. When dealing with a 2D image, for example, the application program must calculate
the pixel offset in the 1­D array that corresponds to any particular X, Y coordinate in the image.
C programmers should note that the ordering of arrays in FITS files, and hence in all the CFITSIO
calls, is more similar to the dimensionality of arrays in Fortran rather than C. For instance if a
FITS image has NAXIS1 = 100 and NAXIS2 = 50, then a 2­D array just large enough to hold the
image should be declared as array[50][100] and not as array[100][50].
For convenience, higher­level routines are also provided to specificly deal with 2D images (ffp2d
and ffg2d ) and 3D data cubes (ffp3d and ffg3d ). The dimensionality of the FITS image is passed
by the naxis1, naxis2, and naxis3 parameters and the declared dimensions of the program array
are passed in the dim1 and dim2 parameters. Note that the dimensions of the program array may
be larger than the dimensions of the FITS array. For example if a FITS image with NAXIS1 =
NAXIS2 = 400 is read into a program array which is dimensioned as 512 x 512 pixels, then the
image will just fill the lower left corner of the array with pixels in the range 1 ­ 400 in the X an
Y directions. This has the effect of taking a contiguous set of pixel value in the FITS array and
writing them to a non­contiguous array in program memory (i.e., there are now some blank pixels
around the edge of the image in the program array).
The most general set of routines (ffpss , ffgsv , and ffgsf ) may be used to transfer a rectangular
subset of the pixels in a FITS N­dimensional image to or from an array which has been declared
in the calling program. The fpixels and lpixels parameters are integer arrays which specify the
starting and ending pixels in each dimension (starting with 1, not 0) of the FITS image that is to
be read or written. It is important to note that these are the starting and ending pixels in the
FITS image, not in the declared array in the program. The array parameter in these routines is
treated simply as a large one­dimensional array of the appropriate datatype containing the pixel
values; The pixel values in the FITS array are read/written from/to this program array in strict
sequence without any gaps; it is up to the calling routine to correctly interpret the dimensionality
of this array. The two FITS reading routines (ffgsv and ffgsf ) also have an `inc' parameter which
defines the data sampling interval in each dimension of the FITS array. For example, if inc[0]=2
and inc[1]=3 when reading a 2­dimensional FITS image, then only every other pixel in the first
dimension and every 3rd pixel in the second dimension will be returned to the 'array' parameter.
Two types of routines are provided to read the data array which differ in the way undefined pixels
are handled. The first type of routines (e.g., ffgpv ) simply return an array of data elements in
which undefined pixels are set equal to a value specified by the user in the `nulval' parameter. An

8.5. SPECIALIZED FITS PRIMARY ARRAY OR IMAGE EXTENSION I/O ROUTINES 117
additional feature of these routines is that if the user sets nulval = 0, then no checks for undefined
pixels will be performed, thus reducing the amount of CPU processing. The second type of routines
(e.g., ffgpf ) returns the data element array and, in addition, a char array which defines whether
the corresponding data pixel is defined (= 1) or not (= 0). The latter type of routines may be more
convenient to use in some circumstances, however, it requires an additional array of logical values
which can be unwieldy when working with large data arrays.
1 Write elements into the data array. The datatype is specified by the suffix of the name of the
routine.
int fits—write—img—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffppr[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, long group, long firstelem, long nelements,
DTYPE *array, ? int *status);
2 Write elements into the data array, substituting the appropriate FITS null value for all elements
which are equal to the value of NULLVAL. For integer FITS arrays, the null value defined
by the BLANK keyword or a previous call to ffpnul will be substituted; for floating point
FITS arrays (BITPIX = ­32 or ­64) then the special IEEE NaN (Not­a­Number) value will
be substituted.
int fits—write—imgnull—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffppn[b,i,ui,k,uk,j,uje,d]
(fitsfile *fptr, long group, long firstelem,
long nelements, DTYPE *array, DTYPE nulval, ? int *status);
3 Set data array elements as undefined.
int fits—write—img—null / ffppru
(fitsfile *fptr, long group, long firstelem, long nelements,
? int *status)
4 Write values into group parameters. This routine only applies to the `Random Grouped' FITS
format which has been used for applications in radio interferometry, but is offically deprecated
for future use.
int fits—write—grppar—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffpgp[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, long group, long firstelem, long nelements,
? DTYPE *array, int *status)
5 Write a 2­D image into the data array.

118 CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES
int fits—write—2d—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffp2d[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, long group, long dim1, long naxis1,
long naxis2, DTYPE *array, ? int *status)
7 Write a 3­D cube into the data array.
int fits—write—3d—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffp3d[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, long group, long dim1, long dim2,
long naxis1, long naxis2, long naxis3, DTYPE *array, ? int *status)
8 Write an arbitrary data subsection into the data array.
int fits—write—subset—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffpss[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, long group, long naxis, long *naxes,
long *fpixel, long *lpixel, DTYPE *array, ? int *status)
9 Read elements from the data array. Undefined array elements will be returned with a value =
nullval, unless nullval = 0 in which case no checks for undefined pixels will be performed.
int fits—read—img—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffgpv[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, long group, long firstelem, long nelements,
DTYPE nulval, ? DTYPE *array, int *anynul, int *status)
10 Read elements and nullflags from data array. Any undefined array elements will have the
corresponding nularray element set equal to 1, else 0.
int fits—read—imgnull—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffgpf[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, long group, long firstelem, long nelements,
? DTYPE *array, char *nularray, int *anynul, int *status)
11 Read values from group parameters. This routine only applies to the `Random Grouped' FITS
format which has been used for applications in radio interferometry, but is offically deprecated
for future use.
int fits—read—grppar—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffggp[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, long group, long firstelem, long nelements,
? DTYPE *array, int *status)

8.6. SPECIALIZED FITS ASCII AND BINARY TABLE ROUTINES 119
12 Read 2­D image from the data array. Undefined pixels in the array will be set equal to the value
of 'nulval', unless nulval=0 in which case no testing for undefined pixels will be performed.
int fits—read—2d—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffg2d[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, long group, DTYPE nulval, long dim1, long naxis1,
long naxis2, ? DTYPE *array, int *anynul, int *status)
13 Read 3­D cube from the data array. Undefined pixels in the array will be set equal to the value
of 'nulval', unless nulval=0 in which case no testing for undefined pixels will be performed.
int fits—read—3d—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffg3d[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, long group, DTYPE nulval, long dim1,
long dim2, long naxis1, long naxis2, long naxis3,
? DTYPE *array, int *anynul, int *status)
14 Read an arbitrary data subsection from the data array. Undefined pixels in the array will be set
equal to the value of 'nulval', unless nullval=0 in which case no testing for undefined pixels
will be performed.
int fits—read—subset—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffgsv[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, int group, int naxis, long *naxes,
long *fpixels, long *lpixels, long *inc, DTYPE nulval,
? DTYPE *array, int *anynul, int *status)
15 Read an arbitrary data subsection from the data array. Any Undefined pixels in the array will
have the corresponding 'nularray' element set equal to TRUE.
int fits—read—subsetnull—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffgsf[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, int group, int naxis, long *naxes,
long *fpixels, long *lpixels, long *inc, ? DTYPE *array,
char *nularray, int *anynul, int *status)
8.6 Specialized FITS ASCII and Binary Table Routines
8.6.1 Column Information Routines
1 Get information about an existing ASCII table column. A null pointer may be given for any of
the output parameters that are not needed.

120 CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES
int fits—get—acolparms / ffgacl
(fitsfile *fptr, int colnum, ? char *ttype, long *tbcol,
char *tunit, char *tform, double *scale, double *zero,
char *nulstr, char *tdisp, int *status)
2 Get information about an existing binary table column. DATATYPE is a character string which
returns the datatype of the column as defined by the TFORMn keyword (e.g., 'I', 'J','E', 'D',
etc.). In the case of an ASCII character column, typecode will have a value of the form 'An'
where 'n' is an integer expressing the width of the field in characters. For example, if TFORM
= '160A8' then ffgbcl will return typechar='A8' and repeat=20. All the returned parameters
are scalar quantities. A null pointer may be given for any of the output parameters that are
not needed.
int fits—get—bcolparms / ffgbcl
(fitsfile *fptr, int colnum, ? char *ttype, char *tunit,
char *typechar, long *repeat, double *scale, double *zero,
long *nulval, char *tdisp, int *status)
3 Return optimal number of rows to read or write at one time for maximum I/O efficiency. Refer
to the ``Optimizing Code'' section in Chapter 5 for more discussion on how to use this routine.
int fits—get—rowsize / ffgrsz
(fitsfile *fptr, long *nrows, *status)
4 Define the zero indexed byte offset of the 'heap' measured from the start of the binary table data.
By default the heap is assumed to start immediately following the regular table data, i.e., at
location NAXIS1 x NAXIS2. This routine is only relevant for binary tables which contain
variable length array columns (with TFORMn = 'Pt'). This routine also automatically writes
the value of theap to a keyword in the extension header. This routine must be called after
the required keywords have been written (with ffphbn) and after the table structure has been
defined (with ffbdef) but before any data is written to the table.
int fits—write—theap / ffpthp
(fitsfile *fptr, long theap, ? int *status)
8.6.2 Low­Level Table Access Routines
The following 2 routines provide low­level access to the data in ASCII or binary tables and are
mainly useful as an efficient way to copy all or part of a table from one location to another. These
routines simply read or write the specified number of consecutive bytes in an ASCII or binary
table, without regard for column boundaries or the row length in the table. These routines do not
perform any machine dependent data conversion or byte swapping.

8.6. SPECIALIZED FITS ASCII AND BINARY TABLE ROUTINES 121
1 Read a consecutive array of bytes from an ASCII or binary table
int fits—read—tblbytes / ffgtbb
(fitsfile *fptr, long firstrow, long firstchar, long nchars,
? unsigned char *values, int *status)
2 Write a consecutive array of bytes to an ASCII or binary table
int fits—write—tblbytes / ffptbb
(fitsfile *fptr, long firstrow, long firstchar, long nchars,
unsigned char *values, ? int *status)
8.6.3 Specialized Write Column Data Routines
1 Write elements into an ASCII or binary table column (in the CDU). The datatype of the array
is implied by the suffix of the routine name.
int fits—write—col—str / ffpcls
(fitsfile *fptr, int colnum, long firstrow, long firstelem,
long nelements, char **array, ? int *status)
int fits—write—col—[log,byt,sht,usht,int,uint,lng,ulng,flt,dbl,cmp,dblcmp] /
ffpcl[l,b,i,ui,k,uk,j,uj,e,d,c,m]
(fitsfile *fptr, int colnum, long firstrow,
long firstelem, long nelements, DTYPE *array, ? int *status)
2 Write elements into an ASCII or binary table column substituting the appropriate FITS null
value for any elements that are equal to the nulval parameter. This routines must not be
used to write to variable length array columns.
int fits—write—colnul—[log, byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffpcn[l,b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, int colnum, long firstrow, long firstelem,
long nelements, DTYPE *array, DTYPE nulval, ? int *status)
3 Write string elements into a binary table column (in the CDU) substituting the FITS null value
for any elements that are equal to the nulstr string. This routine must NOT be used to write
to variable length array columns.
int fits—write—colnul—str / ffpcns
(fitsfile *fptr, int colnum, long firstrow, long firstelem,
long nelements, char **array, char *nulstr, ? int *status)

122 CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES
4 Write bit values into a binary byte ('B') or bit ('X') table column (in the CDU). Larray is an
array of logical values corresponding to the sequence of bits to be written. If larray is true
then the corresponding bit is set to 1, otherwise the bit is set to 0. Note that in the case of
'X' columns, CFITSIO can write to all 8 bits of each byte whether they are formally valid or
not. Thus if the column is defined as '4X', and one calls ffpclx with firstbit=1 and nbits=8,
then all 8 bits will be written into the first byte (as opposed to writing the first 4 bits into
the first row and then the next 4 bits into the next row), even though the last 4 bits of each
byte are formally not defined.
int fits—write—col—bit / ffpclx
(fitsfile *fptr, int colnum, long firstrow, long firstbit,
long nbits, char *larray, ? int *status)
5 Write the descriptor for a variable length column in a binary table. This routine can be used in
conjunction with FFGDES to enable 2 or more arrays to point to the same storage location
to save storage space if the arrays are identical.
int fits—write—descript / ffpdes
(fitsfile *fptr, int colnum, long rownum, long repeat,
long offset, ? int *status)
8.6.4 Specialized Read Column Data Routines
Two types of routines are provided to get the column data which differ in the way undefined pixels
are handled. The first set of routines (ffgcv) simply return an array of data elements in which
undefined pixels are set equal to a value specified by the user in the 'nullval' parameter. If nullval
= 0, then no checks for undefined pixels will be performed, thus increasing the speed of the program.
The second set of routines (ffgcf) returns the data element array and in addition a logical array of
flags which defines whether the corresponding data pixel is undefined.
Any column, regardless of it's intrinsic datatype, may be read as a string. It should be noted
however that reading a numeric column as a string is 10 ­ 100 times slower than reading the same
column as a number due to the large overhead in constructing the formatted strings. The display
format of the returned strings will be determined by the TDISPn keyword, if it exists, otherwise by
the datatype of the column. The length of the returned strings (not including the null terminating
character) can be determined with the fits get col display width routine. The following TDISPn
display formats are currently supported:
Iw.m Integer
Ow.m Octal integer
Zw.m Hexadecimal integer
Fw.d Fixed floating point
Ew.d Exponential floating point
Dw.d Exponential floating point
Gw.d General; uses Fw.d if significance not lost, else Ew.d

8.6. SPECIALIZED FITS ASCII AND BINARY TABLE ROUTINES 123
where w is the width in characters of the displayed values, m is the minimum number of digits
displayed, and d is the number of digits to the right of the decimal. The .m field is optional.
1 Read elements from an ASCII or binary table column (in the CDU). These routines return the
values of the table column array elements. Undefined array elements will be returned with a
value = nulval, unless nulval = 0 (or = ' ' for ffgcvs) in which case no checking for undefined
values will be performed. The ANYF parameter is set to true if any of the returned elements
are undefined.
int fits—read—col—str / ffgcvs
(fitsfile *fptr, int colnum, long firstrow, long firstelem,
long nelements, char *nulstr, ? char **array, int *anynul,
int *status)
int fits—read—col—[log,byt,sht,usht,int,uint,lng,ulng, flt, dbl, cmp, dblcmp] /
ffgcv[l,b,i,ui,k,uk,j,uj,e,d,c,m]
(fitsfile *fptr, int colnum, long firstrow, long firstelem,
long nelements, DTYPE nulval, ? DTYPE *array, int *anynul,
int *status)
2 Read elements and null flags from an ASCII or binary table column (in the CHDU). These
routines return the values of the table column array elements. Any undefined array elements
will have the corresponding nularray element set equal to TRUE. The anynul parameter is
set to true if any of the returned elements are undefined.
int fits—read—colnull—str / ffgcfs
(fitsfile *fptr, int colnum, long firstrow, long firstelem,
long nelements, ? char **array, char *nularray, int *anynul,
int *status)
int fits—read—colnull—[log,byt,sht,usht,int,uint,lng,ulng,flt,dbl,cmp,dblcmp] /
ffgcf[l,b,i,ui,k,uk,j,uj,e,d,c,m]
(fitsfile *fptr, int colnum, long firstrow,
long firstelem, long nelements, ? DTYPE *array,
char *nularray, int *anynul, int *status)
3 Read an arbitrary data subsection from an N­dimensional array in a binary table vector column.
Undefined pixels in the array will be set equal to the value of 'nulval', unless nulval=0 in which
case no testing for undefined pixels will be performed. The first and last rows in the table to
be read are specified by fpixels(naxis+1) and lpixels(naxis+1), and hence are treated as the
next higher dimension of the FITS N­dimensional array. The INC parameter specifies the
sampling interval in each dimension between the data elements that will be returned.
int fits—read—subset—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /

124 CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES
ffgsv[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, int colnum, int naxis, long *naxes, long *fpixels,
long *lpixels, long *inc, DTYPE nulval, ? DTYPE *array, int *anynul,
int *status)
4 Read an arbitrary data subsection from an N­dimensional array in a binary table vector column.
Any Undefined pixels in the array will have the corresponding 'nularray' element set equal
to TRUE. The first and last rows in the table to be read are specified by fpixels(naxis+1)
and lpixels(naxis+1), and hence are treated as the next higher dimension of the FITS N­
dimensional array. The INC parameter specifies the sampling interval in each dimension
between the data elements that will be returned.
int fits—read—subsetnull—[byt, sht, usht, int, uint, lng, ulng, flt, dbl] /
ffgsf[b,i,ui,k,uk,j,uj,e,d]
(fitsfile *fptr, int colnum, int naxis, long *naxes,
long *fpixels, long *lpixels, long *inc, ? DTYPE *array,
char *nularray, int *anynul, int *status)
5 Read bit values from a byte ('B') or bit (`X`) table column (in the CDU). Larray is an array
of logical values corresponding to the sequence of bits to be read. If larray is true then the
corresponding bit was set to 1, otherwise the bit was set to 0. Note that in the case of 'X'
columns, CFITSIO can read all 8 bits of each byte whether they are formally valid or not.
Thus if the column is defined as '4X', and one calls ffgcx with firstbit=1 and nbits=8, then
all 8 bits will be read from the first byte (as opposed to reading the first 4 bits from the first
row and then the first 4 bits from the next row), even though the last 4 bits of each byte are
formally not defined.
int fits—read—col—bit / ffgcx
(fitsfile *fptr, int colnum, long firstrow, long firstbit,
long nbits, ? char *larray, int *status)
6 Read any consecutive set of bits from an 'X' or 'B' column and interpret them as an unsigned
n­bit integer. nbits must be less than 16 or 32 in ffgcxui and ffgcxuk, respectively. If nrows
is greater than 1, then the same set of bits will be read from each row, starting with firstrow.
The bits are numbered with 1 = the most significant bit of the first element of the column.
int fits—read—col—bit—[usht, uint] / ffgcx[ui,uk]
(fitsfile *fptr, int colnum, long firstrow, long, nrows,
long firstbit, long nbits, ? DTYPE *array, int *status)
7 Return the descriptor for a variable length column in a binary table. The descriptor consists of
2 integer parameters: the number of elements in the array and the starting offset relative to
the start of the heap. The first routine returns a single descriptor whereas the second routine
returns the descriptors for a range of rows in the table.

8.6. SPECIALIZED FITS ASCII AND BINARY TABLE ROUTINES 125
int fits—read—descript / ffgdes
(fitsfile *fptr, int colnum, long rownum, ? long *repeat,
long *offset, int *status)
int fits—read—descripts / ffgdess
(fitsfile *fptr, int colnum, long firstrow, long nrows ? long *repeat,
long *offset, int *status)

126 CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES

127

128 APPENDIX A. INDEX OF ROUTINES
Appendix A
Index of Routines
fits add group member 90
fits ascii tform 99
fits binary tform 98
fits calculator 93
fits calculator rng 93
fits calc rows 92
fits change group 88
fits clear errmsg 66
fits close file 67
fits compact group 89
fits compare str 96
fits copy col 81
fits copy data 105
fits copy group 89
fits copy hdu 70
fits copy header 105
fits copy key 109
fits copy member 91
fits create file 67
fits create group 88
fits create hdu 104
fits create img 70
fits create tbl 70
fits create template 67
fits date2str 95
fits decode chksum 94
fits decode tdim 79
fits delete col 81
fits delete file 67
fits delete hdu 70
fits delete key 74
fits delete record 74
fits delete rowlist 80
fits delete rows 80
fits encode chksum 94
fits file mode 68
fits file name 67
fits find first row 92
fits find nextkey 111
fits find rows 92
fits flush file 104
fits get acolparms 119
fits get bcolparms 120
fits get chksum 94
fits get col display width 79
fits get colname 78
fits get colnum 78
fits get coltype 79
fits get errstatus 66
fits get hdrpos 106
fits get hdrspace 71
fits get hdu num 69
fits get hdu type 69
fits get hduaddr 104
fits get img dim 76
fits get img param 76
fits get img size 76
fits get img type 76
fits get keyclass 98
fits get keyname 97
fits get keytype 97
fits get num cols 78
fits get num groups 91
fits get num hdus 69
fits get num members 90
fits get num rows 78
fits get rowsize 120
fits get system time 95
fits get tbcol 99
fits get version 65
fits insert atbl 105
fits insert btbl 105
fits insert col 80
fits insert cols 80
fits insert group 88
fits insert img 104
fits insert key null 111
fits insert key TYP 110
fits insert record 110
fits insert rows 80
fits iterate data 75
fits make keyn 97
fits make nkey 97
fits merge groups 89
fits modify card 113
fits modify comment 73
fits modify key null 114
fits modify key TYP 113
fits modify name 73
fits modify record 113
fits modify vector len 81
fits movabs hdu 69
fits movnam hdu 69
fits movrel hdu 69
fits null check 97
fits open file 66

129
fits open group 90
fits open member 91
fits open memfile 103
fits parse extnum 68
fits parse input url 68
fits parse rootname 68
fits parse template 99
fits parse value 97
fits pix to world 84
fits read 2d TYP 119
fits read 3d TYP 119
fits read atblhdr 107
fits read btblhdr 108
fits read card 73
fits read col 83
fits read col bit 124
fits read col TYP 123
fits read colnull 83
fits read colnull TYP 123
fits read descript 124
fits read descripts 124
fits read errmsg 66
fits read grppar TYP 118
fits read img 77
fits read img coord 84
fits read img TYP 118
fits read imghdr 107
fits read imgnull 77
fits read imgnull TYP 118
fits read key 73
fits read key longstr 112
fits read key triple 113
fits read key unit 74
fits read key TYP 112
fits read keyn 111
fits read keys TYP 112
fits read keyword 112
fits read record 73
fits read subset TYP 119 123
fits read subsetnull TYP 119 124
fits read tbl coord 84
fits read tblbytes 121
fits read tdim 79
fits remove group 89
fits remove member 91
fits reopen file 67
fits report error 66
fits resize img 105
fits select rows 92
fits set atblnull 115
fits set bscale 115
fits set btblnull 115
fits set hdrsize 106
fits set hdustruc 106
fits set imgnull 115
fits set tscale 115
fits str2date 95
fits str2time 95
fits test expr 93
fits test keyword 96
fits test record 96
fits time2str 95
fits transfer member 91
fits update card 72
fits update chksum 94
fits update key 71
fits update key null 72
fits update key TYP 114
fits uppercase 96
fits url type 68
fits verify chksum 94
fits verify group 90
fits world to pix 85
fits write 2d TYP 117
fits write 3d TYP 118
fits write atblhdr 107
fits write btblhdr 107
fits write chksum 94
fits write col 81
fits write col bit 122
fits write col TYP 121
fits write colnull 82
fits write colnull TYP 121
fits write comment 72
fits write date 72
fits write descript 122
fits write errmsg 66
fits write grphdr 106
fits write grppar TYP 117
fits write history 72
fits write img 76
fits write img null 117
fits write img TYP 117
fits write imghdr 106
fits write imgnull 77
fits write imgnull TYP 117
fits write key 71
fits write key longstr 109
fits write key longwarn 109
fits write key null 108
fits write key template 110
fits write key triple 110
fits write key unit 73
fits write key TYP 108
fits write keys TYP 109
fits write null img 77
fits write record 72
fits write subset TYP 118
fits write tblbytes 121
fits write tdim 79
fits write theap 120

130 APPENDIX A. INDEX OF ROUTINES
ffasfm 99
ffbnfm 98
ffcalc 93
ffcalc rng 93
ffclos 67
ffcmps 96
ffcmsg 66
ffcopy 70
ffcpcl 81
ffcpdt 105
ffcphd 105
ffcpky 109
ffcrhd 104
ffcrim 70
ffcrow 92
ffcrtb 70
ffdcol 81
ffdelt 67
ffdhdu 70
ffdkey 74
ffdrec 74
ffdrow 80
ffdrws 80
ffdsum 94
ffdt2s 95
ffdtdm 79
ffdtyp 97
ffesum 94
ffextn 68
ffffrw 92
ffflmd 68
ffflnm 67
ffflus 104
fffrow 92
ffg2d 119
ffg3d 119
ffgabc 99
ffgacl 119
ffgbcl 120
ffgcdw 79
ffgcf 83
ffgcf 123
ffgcks 94
ffgcnn 78
ffgcno 78
ffgcrd 73
ffgcv 83
ffgcv 123
ffgcx 124
ffgdes 124
ffgdess 124
ffgerr 66
ffggp 118
ffghad 104
ffghbn 108
ffghdn 69
ffghdt 69
ffghpr 107
ffghps 106
ffghsp 71
ffghtb 107
ffgics 84
ffgidm 76
ffgidt 76
ffgipr 76
ffgisz 76
ffgkcl 98
ffgkey 112
ffgkls 112
ffgkn 112
ffgknm 97
ffgky 73
ffgkyn 111
ffgkyt 113
ffgky 112
ffgmcp 91
ffgmng 91
ffgmop 91
ffgmrm 91
ffgmsg 66
ffgmtf 91
ffgncl 78
ffgnrw 78
ffgnxk 111
ffgpf 77
ffgpf 118
ffgpv 77
ffgpv 118
ffgrec 73
ffgrsz 120
ffgsdt 95
ffgsf 119 124
ffgstm 95
ffgsv 119 123
ffgtam 90
ffgtbb 121
ffgtch 88
ffgtcl 79
ffgtcm 89
ffgtcp 89
ffgtcr 88
ffgtcs 84
ffgtdm 79
ffgthd 99
ffgtis 88
ffgtmg 89
ffgtnm 90
ffgtop 90
ffgtrm 89
ffgtvf 90
ffgunt 74
ffhdef 106
ffibin 105
fficls 80
fficol 80
ffiimg 104
ffikls 110
ffikyu 111
ffiky 110
ffinit 67
ffirec 110
ffirow 80
ffitab 105
ffiter 75
ffiurl 68
ffkeyn 97
ffmahd 69
ffmcom 73
ffmcrd 113
ffmkls 113
ffmkyu 114
ffmky 113
ffmnam 73
ffmnhd 69
ffmrec 113
ffmrhd 69
ffmvec 81
ffnchk 97
ffnkey 97
ffomem 103
ffopen 66
ffp2d 117
ffp3d 118
ffpcks 94
ffpcl 81
ffpcls 121
ffpcl 122
ffpcn 82
ffpcn 121
ffpcom 72
ffpdat 72
ffpdes 122
ffpgp 117
ffphbn 107
ffphis 72
ffphpr 106
ffphps 106
ffphtb 107
ffpkls 109
ffpkn 109
ffpktp 110
ffpky 71
ffpkyt 110
ffpkyu 108
ffpky 108
ffplsw 109
ffpmsg 66
ffpnul 115
ffppn 77
ffppn 117
ffppr 76
ffpprn 77
ffppru 117
ffppr 117
ffprec 72
ffpscl 115
ffpss 118
ffpsvc 97
ffptbb 121
ffptdm 79
ffpthp 120
ffpunt 73
ffrdef 106
ffreopen 67
ffrprt 66
ffrsim 105
ffrtnm 68
ffs2dt 95
ffs2tm 95
ffsnul 115
ffsrow 92
fftexp 93
ffthdu 69
fftkey 96
fftm2s 95
fftnul 115
fftplt 67
fftrec 96
fftscl 115
ffucrd 72
ffukls 114
ffuky 71
ffukyu 72
ffuky 114
ffupch 96
ffupck 94
ffurlt 68
ffvcks 94
ffvers 65
ffwldp 84
ffxypx 85

Appendix B
Parameter Definitions
anynul ­ set to TRUE (=1) if any returned values are undefined, else FALSE
array ­ array of numerical data values to read or write
ascii ­ encoded checksum string
binspec ­ the input table binning specifier
bitpix ­ bits per pixel. The following symbolic mnemonics are predefined:
BYTE—IMG = 8 (unsigned char)
SHORT—IMG = 16 (signed short integer)
LONG—IMG = 32 (signed long integer)
FLOAT—IMG = ­32 (float)
DOUBLE—IMG = ­64 (double).
Two additional values, USHORT—IMG and ULONG—IMG are also available
for creating unsigned integer images. These are equivalent to
creating a signed integer image with BZERO offset keyword values
of 32768 or 2147483648, respectively, which is the convention that
FITS uses to store unsigned integers.
card ­ header record to be read or written (80 char max, null­terminated)
casesen ­ CASESEN (=1) for case­sensitive string matching, else CASEINSEN (=0)
cmopt ­ grouping table ''compact'' option parameter. Allowed values are:
OPT—CMT—MBR and OPT—CMT—MBR—DEL.
colname ­ name of the column (null­terminated)
colnum ­ column number (first column = 1)
colspec ­ the input file column specification; used to delete, create, or rename
table columns
comment ­ the keyword comment field (72 char max, null­terminated)
complm ­ should the checksum be complemented?
coordtype­ type of coordinate projection (­SIN, ­TAN, ­ARC, ­NCP,
­GLS, ­MER, or ­AIT)
cpopt ­ grouping table copy option parameter. Allowed values are:
OPT—GCP—GPT, OPT—GCP—MBR, OPT—GCP—ALL, OPT—MCP—ADD, OPT—MCP—NADD,
OPT—MCP—REPL, amd OPT—MCP—MOV.
131

132 APPENDIX B. PARAMETER DEFINITIONS
create—col­ If TRUE, then insert a new column in the table, otherwise
overwrite the existing column.
dataok ­ was the data unit verification successful (=1) or
not (= ­1). Equals zero if the DATASUM keyword is not present.
datasum ­ 32­bit 1's complement checksum for the data unit
dataend ­ address (in bytes) of the end of the HDU
datastart­ address (in bytes) of the start of the data unit
datatype ­ specifies the datatype of the value. Allowed value are:
TSTRING, TLOGICAL, TBYTE, TSHORT, TUSHORT, TINT, TUINT, TLONG, TULONG,
TFLOAT, TDOUBLE, TCOMPLEX, and TDBLCOMPLEX
datestr ­ FITS date/time string: 'YYYY­MM­DDThh:mm:ss.ddd', 'YYYY­MM­dd',
or 'dd/mm/yy'
day ­ calendar day (UTC) (1­31)
decimals ­ number of decimal places to be displayed
delta—size ­ increment for allocating more memory
dim1 ­ declared size of the first dimension of the image or cube array
dim2 ­ declared size of the second dimension of the data cube array
dispwidth ­ display width of a column = length of string that will be read
dtype ­ datatype of the keyword ('C', 'L', 'I', 'F' or 'X')
C = character string
L = logical
I = integer
F = floating point number
X = complex, e.g., ''(1.23, ­4.56)''
err—msg ­ error message on the internal stack (80 chars max)
err—text ­ error message string corresponding to error number (30 chars max)
exact ­ TRUE (=1) if the strings match exactly;
FALSE (=0) if wildcards are used
exclist ­ array of pointers to keyword names to be excluded from search
expr ­ boolean or arithmetic expression
extend ­ TRUE (=1) if FITS file may have extensions, else FALSE (=0)
extname ­ value of the EXTNAME keyword (null­terminated)
extspec ­ the extension or HDU specifier; a number or name, version, and type
extvers ­ value of the EXTVERS keyword = integer version number
filename ­ full name of the FITS file, including optional HDU and filtering specs
filetype ­ type of file (file://, ftp://, http://, etc.)
filter ­ the input file filtering specifier
firstchar­ starting byte in the row (first byte of row = 1)
firstfailed ­ member HDU ID (if positive) or grouping table GRPIDn index
value (if negative) that failed grouping table verification.
firstelem­ first element in a vector (ignored for ASCII tables)
firstrow ­ starting row number (first row of table = 1)
fpixels ­ the first included pixel in each dimension (first pixel = 1)
fptr ­ pointer to a 'fitsfile' structure describing the FITS file.
frac ­ factional part of the keyword value

133
gcount ­ number of groups in the primary array (usually = 1)
gfptr ­ fitsfile* pointer to a grouping table HDU.
group ­ GRPIDn/GRPLCn index value identifying a grouping table HDU, or
data group number (=0 for non­grouped data)
grouptype ­ Grouping table parameter that specifies the columns to be
created in a grouing table HDU. Allowed values are: GT—ID—ALL—URI,
GT—ID—REF, GT—ID—POS, GT—ID—ALL, GT—ID—REF—URI, and GT—ID—POS—URI.
grpname ­ value to use for the GRPNAME keyword value.
hdunum ­ sequence number of the HDU (Primary array = 1)
hduok ­ was the HDU verification successful (=1) or
not (= ­1). Equals zero if the CHECKSUM keyword is not present.
hdusum ­ 32 bit 1's complement checksum for the entire CHDU
hdutype ­ type of HDU: IMAGE—HDU (=0), ASCII—TBL (=1), or BINARY—TBL (=2)
headstart­ starting address (in bytes) of the CHDU
history ­ the HISTORY keyword comment string (70 char max, null­terminated)
hour ­ hour within day (UTC) (0 ­ 23)
inc ­ sampling interval for pixels in each FITS dimension
inclist ­ array of pointers to matching keyword names
incolnum ­ input column number; range = 1 to TFIELDS
infile ­ the input filename, including path if specified
infptr ­ pointer to a 'fitsfile' structure describing the input FITS file.
intval ­ integer part of the keyword value
iomode ­ file access mode: either READONLY (=0) or READWRITE (=1)
keyname ­ name of a keyword (8 char max, null­terminated)
keynum ­ position of keyword in header (1st keyword = 1)
keyroot ­ root string for the keyword name (5 char max, null­terminated)
keysexist­ number of existing keyword records in the CHU
keytype ­ header record type: ­1=delete; 0=append or replace;
1=append; 2=this is the END keyword
longstr ­ arbitrarily long string keyword value (null­terminated)
lpixels ­ the last included pixel in each dimension (first pixel = 1)
match ­ TRUE (=1) if the 2 strings match, else FALSE (=0)
maxdim ­ maximum number of values to return
member ­ row number of a grouping table member HDU.
memptr ­ pointer to the a FITS file in memory
mem—realloc ­ pointer to a function for reallocating more memory
mem—size ­ size of the memory block allocated for the FITS file
mfptr ­ fitsfile* pointer to a grouping table member HDU.
mgopt ­ grouping table merge option parameter. Allowed values are:
OPT—MRG—COPY, and OPT—MRG—MOV.
minute ­ minute within hour (UTC) (0 ­ 59)
month ­ calendar month (UTC) (1 ­ 12)
morekeys ­ space in the header for this many more keywords
n—good—rows ­ number of rows evaluating to TRUE
naxes ­ size of each dimension in the FITS array

134 APPENDIX B. PARAMETER DEFINITIONS
naxis ­ number of dimensions in the FITS array
naxis1 ­ length of the X/first axis of the FITS array
naxis2 ­ length of the Y/second axis of the FITS array
naxis3 ­ length of the Z/third axis of the FITS array
nchars ­ number of characters to read or write
nelements­ number of data elements to read or write
newfptr ­ returned pointer to the reopened file
newveclen­ new value for the column vector repeat parameter
nexc ­ number of names in the exclusion list (may = 0)
nfound ­ number of keywords found (highest keyword number)
nkeys ­ number of keywords in the sequence
ninc ­ number of names in the inclusion list
nmembers ­ Number of grouping table members (NAXIS2 value).
nmove ­ number of HDUs to move (+ or ­), relative to current position
nrows ­ number of rows in the table
nstart ­ first integer value
nularray ­ set to TRUE (=1) if corresponding data element is undefined
nulval ­ numerical value to represent undefined pixels
nulstr ­ character string used to represent undefined values in ASCII table
numval ­ numerical data value, of the appropriate datatype
offset ­ byte offset in the heap to the first element of the vector
openfptr ­ pointer to a currently open FITS file
outcolnum­ output column number; range = 1 to TFIELDS + 1
outfile ­ and optional output filename; the input file will be copied to this prior
to opening the file
outfptr ­ pointer to a 'fitsfile' structure describing the output FITS file.
pcount ­ value of the PCOUNT keyword = size of binary table heap
repeat ­ length of column vector (e.g. 12J); == 1 for ASCII table
rmopt ­ grouping table remove option parameter. Allowed values are:
OPT—RM—GPT, OPT—RM—ENTRY, OPT—RM—MBR, and OPT—RM—ALL.
rootname ­ root filename, minus any extension or filtering specifications
rot ­ celestial coordinate rotation angle (degrees)
rowlen ­ length of a table row, in characters or bytes
rowlist ­ sorted list of row numbers to be deleted from the table
rownum ­ number of the row (first row = 1)
row—status ­ array of True/False results for each row that was evaluated
scale ­ linear scaling factor; true value = (FITS value) * scale + zero
second ­ second within minute (0 ­ 60.9999999999) (leapsecond!)
simple ­ TRUE (=1) if FITS file conforms to the Standard, else FALSE (=0)
space ­ number of blank spaces to leave between ASCII table columns
status ­ returned error status code (0 = OK)
sum ­ 32 bit unsigned checksum value
tbcol ­ byte position in row to start of column (1st col has tbcol = 1)
tdisp ­ Fortran style display format for the table column
tdimstr ­ the value of the TDIMn keyword

135
templt ­ template string used in comparison (null­terminated)
tfields ­ number of fields (columns) in the table
tfopt ­ grouping table member transfer option parameter. Allowed values are:
OPT—MCP—ADD, and OPT—MCP—MOV.
tform ­ format of the column (null­terminated); allowed values are:
ASCII tables: Iw, Aw, Fww.dd, Eww.dd, or Dww.dd
Binary tables: rL, rX, rB, rI, rJ, rA, rAw, rE, rD, rC, rM
where 'w'=width of the field, 'd'=no. of decimals, 'r'=repeat count.
Variable length array columns are denoted by a '1P' before the datatype
character (e.g., '1PJ'). When creating a binary table, 2 addition tform
datatype codes are recognized by CFITSIO: 'rU' and 'rV' for unsigned
16­bit and unsigned 32­bit integer, respectively.
theap ­ zero indexed byte offset of starting address of the heap
relative to the beginning of the binary table data
ttype ­ label or name for table column (null­terminated)
tunit ­ physical unit for table column (null­terminated)
typechar ­ symbolic code of the table column datatype
typecode ­ datatype code of the table column. The negative of
the value indicates a variable length array column.
Datatype typecode Mnemonic
bit, X 1 TBIT
byte, B 11 TBYTE
logical, L 14 TLOGICAL
ASCII character, A 16 TSTRING
short integer, I 21 TSHORT
integer, J 41 TLONG
real, E 42 TFLOAT
double precision, D 82 TDOUBLE
complex, C 83 TCOMPLEX
double complex, M 163 TDBLCOMPLEX
unit ­ the physical unit string (e.g., 'km/s') for a keyword
urltype ­ the file type of the FITS file (file://, ftp://, mem://, etc.)
value ­ the keyword value string (70 char max, null­terminated)
version ­ current version number of the CFITSIO library
width ­ width of the character string field
xcol ­ number of the column containing the X coordinate values
xinc ­ X axis coordinate increment at reference pixel (deg)
xpix ­ X axis pixel location
xpos ­ X axis celestial coordinate (usually RA) (deg)
xrefpix ­ X axis reference pixel array location
xrefval ­ X axis coordinate value at the reference pixel (deg)
ycol ­ number of the column containing the X coordinate values
year ­ calendar year (e.g. 1999, 2000, etc)
yinc ­ Y axis coordinate increment at reference pixel (deg)

136 APPENDIX B. PARAMETER DEFINITIONS
ypix ­ y axis pixel location
ypos ­ y axis celestial coordinate (usually DEC) (deg)
yrefpix ­ Y axis reference pixel array location
yrefval ­ Y axis coordinate value at the reference pixel (deg)
zero ­ scaling offset; true value = (FITS value) * scale + zero

Appendix C
CFITSIO Error Status Codes
The following table lists all the error status codes used by CFITSIO. Programmers are encouraged
to use the symbolic mnemonics (defined in the file fitsio.h) rather than the actual integer status
values to improve the readability of their code.
Symbolic Const Value Meaning
­­­­­­­­­­­­­­ ­­­­­ ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
0 OK, no error
SAME—FILE 101 input and output files are the same
TOO—MANY—FILES 103 tried to open too many FITS files at once
FILE—NOT—OPENED 104 could not open the named file
FILE—NOT—CREATED 105 could not create the named file
WRITE—ERROR 106 error writing to FITS file
END—OF—FILE 107 tried to move past end of file
READ—ERROR 108 error reading from FITS file
FILE—NOT—CLOSED 110 could not close the file
ARRAY—TOO—BIG 111 array dimensions exceed internal limit
READONLY—FILE 112 Cannot write to readonly file
MEMORY—ALLOCATION 113 Could not allocate memory
BAD—FILEPTR 114 invalid fitsfile pointer
NULL—INPUT—PTR 115 NULL input pointer to routine
SEEK—ERROR 116 error seeking position in file
BAD—URL—PREFIX 121 invalid URL prefix on file name
TOO—MANY—DRIVERS 122 tried to register too many IO drivers
DRIVER—INIT—FAILED 123 driver initialization failed
NO—MATCHING—DRIVER 124 matching driver is not registered
URL—PARSE—ERROR 125 failed to parse input file URL
SHARED—BADARG 151 bad argument in shared memory driver
SHARED—NULPTR 152 null pointer passed as an argument
SHARED—TABFULL 153 no more free shared memory handles
137

138 APPENDIX C. CFITSIO ERROR STATUS CODES
SHARED—NOTINIT 154 shared memory driver is not initialized
SHARED—IPCERR 155 IPC error returned by a system call
SHARED—NOMEM 156 no memory in shared memory driver
SHARED—AGAIN 157 resource deadlock would occur
SHARED—NOFILE 158 attempt to open/create lock file failed
SHARED—NORESIZE 159 shared memory block cannot be resized at the moment
HEADER—NOT—EMPTY 201 header already contains keywords
KEY—NO—EXIST 202 keyword not found in header
KEY—OUT—BOUNDS 203 keyword record number is out of bounds
VALUE—UNDEFINED 204 keyword value field is blank
NO—QUOTE 205 string is missing the closing quote
BAD—KEYCHAR 207 illegal character in keyword name or card
BAD—ORDER 208 required keywords out of order
NOT—POS—INT 209 keyword value is not a positive integer
NO—END 210 couldn't find END keyword
BAD—BITPIX 211 illegal BITPIX keyword value
BAD—NAXIS 212 illegal NAXIS keyword value
BAD—NAXES 213 illegal NAXISn keyword value
BAD—PCOUNT 214 illegal PCOUNT keyword value
BAD—GCOUNT 215 illegal GCOUNT keyword value
BAD—TFIELDS 216 illegal TFIELDS keyword value
NEG—WIDTH 217 negative table row size
NEG—ROWS 218 negative number of rows in table
COL—NOT—FOUND 219 column with this name not found in table
BAD—SIMPLE 220 illegal value of SIMPLE keyword
NO—SIMPLE 221 Primary array doesn't start with SIMPLE
NO—BITPIX 222 Second keyword not BITPIX
NO—NAXIS 223 Third keyword not NAXIS
NO—NAXES 224 Couldn't find all the NAXISn keywords
NO—XTENSION 225 HDU doesn't start with XTENSION keyword
NOT—ATABLE 226 the CHDU is not an ASCII table extension
NOT—BTABLE 227 the CHDU is not a binary table extension
NO—PCOUNT 228 couldn't find PCOUNT keyword
NO—GCOUNT 229 couldn't find GCOUNT keyword
NO—TFIELDS 230 couldn't find TFIELDS keyword
NO—TBCOL 231 couldn't find TBCOLn keyword
NO—TFORM 232 couldn't find TFORMn keyword
NOT—IMAGE 233 the CHDU is not an IMAGE extension
BAD—TBCOL 234 TBCOLn keyword value ! 0 or ? rowlength
NOT—TABLE 235 the CHDU is not a table
COL—TOO—WIDE 236 column is too wide to fit in table
COL—NOT—UNIQUE 237 more than 1 column name matches template
BAD—ROW—WIDTH 241 sum of column widths not = NAXIS1
UNKNOWN—EXT 251 unrecognizable FITS extension type

139
UNKNOWN—REC 252 unknown record; 1st keyword not SIMPLE or XTENSION
END—JUNK 253 END keyword is not blank
BAD—HEADER—FILL 254 Header fill area contains non­blank chars
BAD—DATA—FILL 255 Illegal data fill bytes (not zero or blank)
BAD—TFORM 261 illegal TFORM format code
BAD—TFORM—DTYPE 262 unrecognizable TFORM datatype code
BAD—TDIM 263 illegal TDIMn keyword value
BAD—HDU—NUM 301 HDU number ! 1 or ? MAXHDU
BAD—COL—NUM 302 column number ! 1 or ? tfields
NEG—FILE—POS 304 tried to move to negative byte location in file
NEG—BYTES 306 tried to read or write negative number of bytes
BAD—ROW—NUM 307 illegal starting row number in table
BAD—ELEM—NUM 308 illegal starting element number in vector
NOT—ASCII—COL 309 this is not an ASCII string column
NOT—LOGICAL—COL 310 this is not a logical datatype column
BAD—ATABLE—FORMAT 311 ASCII table column has wrong format
BAD—BTABLE—FORMAT 312 Binary table column has wrong format
NO—NULL 314 null value has not been defined
NOT—VARI—LEN 317 this is not a variable length column
BAD—DIMEN 320 illegal number of dimensions in array
BAD—PIX—NUM 321 first pixel number greater than last pixel
ZERO—SCALE 322 illegal BSCALE or TSCALn keyword = 0
NEG—AXIS 323 illegal axis length ! 1
NOT—GROUP—TABLE 340 Grouping function error
HDU—ALREADY—MEMBER 341
MEMBER—NOT—FOUND 342
GROUP—NOT—FOUND 343
BAD—GROUP—ID 344
TOO—MANY—HDUS—TRACKED 345
HDU—ALREADY—TRACKED 346
BAD—OPTION 347
IDENTICAL—POINTERS 348
NGP—NO—MEMORY 360 malloc failed
NGP—READ—ERR 361 read error from file
NGP—NUL—PTR 362 null pointer passed as an argument.
Passing null pointer as a name of
template file raises this error
NGP—EMPTY—CURLINE 363 line read seems to be empty (used
internally)
NGP—UNREAD—QUEUE—FULL 364 cannot unread more then 1 line (or single
line twice)
NGP—INC—NESTING 365 too deep include file nesting (infinite

140 APPENDIX C. CFITSIO ERROR STATUS CODES
loop, template includes itself ?)
NGP—ERR—FOPEN 366 fopen() failed, cannot open template file
NGP—EOF 367 end of file encountered and not expected
NGP—BAD—ARG 368 bad arguments passed. Usually means
internal parser error. Should not happen
NGP—TOKEN—NOT—EXPECT 369 token not expected here
BAD—I2C 401 bad int to formatted string conversion
BAD—F2C 402 bad float to formatted string conversion
BAD—INTKEY 403 can't interpret keyword value as integer
BAD—LOGICALKEY 404 can't interpret keyword value as logical
BAD—FLOATKEY 405 can't interpret keyword value as float
BAD—DOUBLEKEY 406 can't interpret keyword value as double
BAD—C2I 407 bad formatted string to int conversion
BAD—C2F 408 bad formatted string to float conversion
BAD—C2D 409 bad formatted string to double conversion
BAD—DATATYPE 410 illegal datatype code value
BAD—DECIM 411 bad number of decimal places specified
NUM—OVERFLOW 412 overflow during datatype conversion
DATA—COMPRESSION—ERR 413 error compressing image
DATA—DECOMPRESSION—ERR 414 error uncompressing image
BAD—DATE 420 error in date or time conversion
PARSE—SYNTAX—ERR 431 syntax error in parser expression
PARSE—BAD—TYPE 432 expression did not evaluate to desired type
PARSE—LRG—VECTOR 433 vector result too large to return in array
PARSE—NO—OUTPUT 434 data parser failed not sent an out column
PARSE—BAD—COL 435 bad data encounter while parsing column
PARSE—BAD—OUTPUT 436 Output file not of proper type
ANGLE—TOO—BIG 501 celestial angle too large for projection
BAD—WCS—VAL 502 bad celestial coordinate or pixel value
WCS—ERROR 503 error in celestial coordinate calculation
BAD—WCS—PROJ 504 unsupported type of celestial projection
NO—WCS—KEY 505 celestial coordinate keywords not found
APPROX—WCS—KEY 506 approximate wcs keyword values were returned