Документ взят из кэша поисковой машины. Адрес оригинального документа : http://vega.inp.nsk.su/~inest/OCAAS/cfitsio.pdf
Дата изменения: Sun Oct 13 19:10:26 2002
Дата индексирования: Mon Oct 1 19:55:38 2012
Кодировка:

Поисковые слова: http www.badastronomy.com phpbb index.php
CFITSIO User's Guide
An Interface to FITS Format Files for C Programmers
Version 2.0

HEASARC Code 662 Goddard Space FlightCenter Greenbelt, MD 20771 USA

February 2000



Contents
1 Introduction 2 Creating the CFITSIO Library
2.1 Building the Library 2.1.1 Unix Systems 2.1.2 VMS 2.1.3 Windows PCs 2.1.4 OS/2 2.1.5 Macintosh PCs 2.2 Testing the Library 2.3 Linking Programs with CFITSIO 2.4 Getting Started with CFITSIO 2.5 Example Program 2.6 Acknowledgements
:::::::::::::::::::::::::::::::::::: :::::::::::::::::::::::::::::::::::

1 3
3 3 5 5 5 5 6 7 7 8 9

::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::

:::::::::::::::::::::::::::::::::::::::: :::::::::::::::::::::::::::::::::::

::::::::::::::::::::::::::::::::::::: :::::::::::::::::::::::::::::

::::::::::::::::::::::::::::::

::::::::::::::::::::::::::::::::::::: :::::::::::::::::::::::::::::::::::::

3 A FITS Primer 4 Extended File Name Syntax
4.1 Overview 4.2 Detailed Filename Syntax 4.2.1 Filetype 4.2.2 Base Filename 4.2.3 Output File Name when Opening an Existing File 4.2.4 Template File Name when Creating a New File 4.2.5 HDU Location Speci cation i
:::::::::::::::::::::::::::::::::::::::::: :::::::::::::::::::::::::::::::::

11 13
13 15 16 19 20 21 25

::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::: :::::::::::::::

:::::::::::::::::

::::::::::::::::::::::::::::


ii 4.2.6 4.2.7 4.2.8 4.2.9 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 5.12 5.13 5.14 Image Section Column and Keyword Filtering Speci cation Row Filtering Speci cation Binning or Histogramming Speci cation

CONTENTS
:::::::::::::::::::::::::::::::::::: ::::::::::::::::::

:::::::::::::::::::::::::::: :::::::::::::::::::::

26 27 28 35

5 CFITSIO Conventions and Guidelines

CFITSIO De nitions CFITSIO Size Limitations Multiple Access to the Same FITS File Current Header Data Unit (CHDU) Function Names and Datatypes Unsigned Integers Character Strings Implicit Data Type Conversion Data Scaling Error Status Values and the Error Message Stack Variable-Length Arrays in Binary Tables Support for IEEE Special Values When the Final Size of the FITS HDU is Unknown Local FITS Conventions supported by CFITSIO 5.14.1 Long String Keyword Values. 5.14.2 Arrays of Fixed-Length Strings in Binary Tables 5.14.3 Keyword Units Strings 5.14.4 HIERARCH Convention for Extended Keyword Names 5.15 Optimizing Code for Maximum Processing Speed 5.15.1 Background Information: How CFITSIO Manages Data I/O 5.15.2 Optimization Strategies 6.1 The Iterator Work Function 6.2 The Iterator Driver Function 6.3 Guidelines for Using the Iterator Function

39

:::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::

:::::::::::::::::::::::::::

::::::::::::::::::::::::::::::

:::::::::::::::::::::::::::::::::::::: :::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::

:::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::

:::::::::::::::::::::::::

::::::::::::::::::::::::::::: :::::::::::::::::::

::::::::::::::::::::

::::::::::::::::::::::::::: ::::::::::::::::

::::::::::::::::::::::::::::::: ::::::::::::

:::::::::::::::::::: :::::::::

::::::::::::::::::::::::::::::

39 41 42 42 42 44 46 47 47 47 48 50 50 51 51 52 52 53 54 54 55 60 62 63

6 The CFITSIO Iterator Function

59

:::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::: ::::::::::::::::::::::::


CONTENTS

iii

7 Basic CFITSIO Interface Routines
7.1 7.2 7.3 7.4 7.5 7.6 7.7

7.8

7.9 7.10 7.11 7.12 7.13

CFITSIO Error Status Routines FITS File Access Routines HDU Access Routines Header Keyword Read/Write Routines Iterator Routines Primary Array or IMAGE Extension I/O Routines ASCII and Binary Table Routines 7.7.1 Column Information Routines 7.7.2 Routines to Edit Rows or Columns 7.7.3 Read and Write Column Data Routines Celestial Coordinate System Routines 7.8.1 Self-contained WCS Routines 7.8.2 WCS Routines that require the WCS library Hierarchical Grouping Convention Support Routines Row Selection and Calculator Routines File Checksum Routines Date and Time UtilityRoutines General Utility Routines

65

:::::::::::::::::::::::::::::

:::::::::::::::::::::::::::::::::

::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::

:::::::::::::::::::::::::::::::::::::: :::::::::::::::::::

:::::::::::::::::::::::::::: :::::::::::::::::::::::::: ::::::::::::::::::::::: :::::::::::::::::::::

:::::::::::::::::::::::::: :::::::::::::::::::::::::: :::::::::::::::::: ::::::::::::::::::

::::::::::::::::::::::::::

:::::::::::::::::::::::::::::::::: :::::::::::::::::::::::::::::

:::::::::::::::::::::::::::::::::

65 66 69 71 74 76 77 78 80 81 83 84 85 87 92 93 95 96

8 Specialized CFITSIO Interface Routines

8.1 Specialized FITS File Access Routines 8.2 Specialized HDU Access Routines 8.3 Specialized Header Keyword Routines 8.3.1 Header Information Routines 8.3.2 Read and Write the Required Keywords 8.3.3 Specialized Write Keyword Routines 8.3.4 Insert Keyword Routines 8.3.5 Specialized Read Keyword Routines 8.3.6 Modify Keyword Routines 8.3.7 Specialized Update Keyword Routines 8.4 De ne Data Scaling and Unde ned Pixel Parameters

103
103 104 106 106 106 108 110 111 113 114 114

::::::::::::::::::::::::::

::::::::::::::::::::::::::::: ::::::::::::::::::::::::::

::::::::::::::::::::::::::: :::::::::::::::::::::

:::::::::::::::::::::::

::::::::::::::::::::::::::::: :::::::::::::::::::::::

:::::::::::::::::::::::::::: ::::::::::::::::::::: ::::::::::::::::::


iv 8.5 Specialized FITS Primary Arrayor IMAGE Extension I/O Routines 8.6 Specialized FITS ASCII and Binary Table Routines 8.6.1 Column Information Routines 8.6.2 Low-Level Table Access Routines 8.6.3 Specialized Write Column Data Routines 8.6.4 Specialized Read Column Data Routines

CONTENTS
::::::::: ::::::::::::::::::

::::::::::::::::::::::::::: :::::::::::::::::::::::: ::::::::::::::::::::

:::::::::::::::::::::

116 119 119 120 121 122

A Index of Routines B Parameter De nitions C CFITSIO Error Status Codes

127 131 137


Chapter 1

Introduction
CFITSIO is a machine-independent library of routines for reading and writing data les in the FITS (Flexible Image Transport System) data format. It can also read IRAF format image les by converting them on the y into a temporary FITS format le. This library is written in ANSI C and provides a powerful yet simple interface for accessing FITS les which will run on most commonly used computers and workstations. CFITSIO supports all the features described in the o cial NOST de nition of the FITS format and can read and write all the currently de ned types of extensions, including ASCII tables (TABLE), Binary tables (BINTABLE) and IMAGE extensions. The CFITSIO routines insulate the programmer from having to deal with the complicated formatting details in the FITS le, however, it is assumed that users have a general knowledge about the structure and usage of FITS les. 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 de nition 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 pro ject in The Netherlands made especially signi cant 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
Dr. William Pence HEASARC, Code 662 NASA/Goddard Space Flight Center Greenbelt, MD 20771, USA

CHAPTER 1. INTRODUCTION
Telephone: (301) 286-4599 E-mail: pence@tetra.gsfc.nasa.gov

This User's Guide assumes that readers already have a general understanding of the de nition and structure of FITS format les. Further information about FITS formats is available in the `FITS User's Guide' and the `NOST FITS Standard', whichare available from the NASA Science O ce 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/ ts 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 les. 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 les (*.c) and header les (*.h). On VAX/VMS systems 2 assembly-code les (vmsieeed.mar and vmsieeer.mar) are also needed. CFITSIO has currently been tested on the following platforms:
OPERATING SYSTEM Sun OS Sun Solaris Silicon Graphics IRIX Dec Alpha OSF/1 DECstation Ultrix Dec Alpha OpenVMS DEC VAX/VMS HP-UX IBM AIX Linux MkLinux Windows 95/98 Windows NT OS/2 MacOS 7.1 or greater COMPILER gcc and cc (3.0.1) gcc and cc gcc and cc gcc and cc gcc cc gcc and cc gcc gcc gcc DR3 Borland C++ V4.5 Microsoft Visual C++ v5.0, v6.0 gcc + EMX Metrowerks 10.+

CFITSIO will probably run on most other Unix platforms. Cray supercomputers and IBM mainframe computers are currently not supported.

2.1.1 Unix Systems
The CFITSIO library is built on Unix systems bytyping: 3


4
> ./configure > make

CHAPTER 2. CREATING THE CFITSIO LIBRARY

at the operating system prompt. Type ./con gure and not simply `con gure' to ensure that the con gure script in the current directory is run and not some other system-wide con gure script. The con gure command customizes the Make le for the particular system, then the `make' command compiles the source les and builds the library. On HP/UX systems, the environmentvariable CFLAGS should be set to -Ae before running congure 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 bytyping 'make all-no tsio' 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 les). It is possible to make both a dynamic and a static version of the CFITSIO library, but network le access will not be possible using the static version. To build the dynamic libc tsio.so library (on solaris), type 'make clean', then edit the Make le 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 libc tsio.a library le do another make clean, unde ne 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. 2. Less disk space if you build more than 1 program 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. 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). No run-time penalty.

3.

4.

The disadvantages are:


2.1. BUILDING THE LIBRARY
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.

5

2.1.2 VMS
On VAX/VMS and ALPHA/VMS systems the make.com command le may be used to build the c tsio.olb ob ject library using the default G- oating point option for double variables. The make d oat.com and make ieee.com les may be used instead to build the library with the other oating 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 le c tsio dll.zip. This zip archivealsocontains other les and instructions on how to use the CFITSIO DLL library. The CFITSIO library may be built using a suitable compiler. The makepc.bat le gives an example of how to build CFITSIO with the Borland C++ v4.5 compiler. This le will probably need to be edited to include the appropriate command switches if a di erent C compiler or linker is used. The les c tsio.dsp, c tsio.dsw, and cookbook.dsp contain the Microsoft Developer workspace les 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 make le.os2'. This make le requires the GCC compiler and EMX library, which are available from manyInternet sites containing OS/2 software, suchas
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 unstu c tsio mac.sit.hqx, (2) put CFitsioPPC.mcp in the c tsio directory, and (3) load CFitsioPPC.mcp into CodeWarrior Pro 2 and make. This builds the c tsio 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 C tsio PPC.lib to your CodeWarrior Pro 2 pro ject. 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 le called `testprog. t' that is identical to the `testprog.std' FITS le included with this release. The diagnostic messages (whichwere piped to the le testprog.lis in the Unix example) should be identical to the listing contained in the le testprog.out. The 'di ' and 'cmp' commands shown above should not report any di erences in the les. (There may be some minor formating di erences, 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 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 (under SUN O/S)

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 di er 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 rst 4 of these utility programs can be compiled and linked bytyping
% make program_name

2.3 Linking Programs with CFITSIO
When linking applications software with the CFITSIO library,several system libraries usually need to be speci ed 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 con gure 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 le access). These latter 2 libraries are not needed on VMS and Windows platforms, because FTP le 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 de nitions in tsio.h often change.

2.4 Getting Started with CFITSIO
In order to e ectively 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 les. 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 tscopy.c programs that are included with this release for examples of routines that perform various common FITS le 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 le 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 le, containing a FITS image. An `EXPOSURE' keyword is written to the header, then the image data are writen to the FITS le before closing the FITS le.
#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
/* Write the array of integers to the image */ fits_write_img(fptr, TSHORT, fpixel, nelements, array 0], &status) fits_close_file(fptr, &status) fits_report_error(stderr, status) return( status ) } /* close the file */ /* print out any error messages */

9

2.6 Acknowledgements
The development of manyof the powerful features in CFITSIO was made possible through collaborations with many people or organizations from around the world. The following, in particular, have made especially signi cantcontributions: 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 simpli ed the low-level I/O, which in turn made other new features in CFITSIO (e.g., support for compressed FITS les and support for IRAF format image les) much easier to implement. Jurek Borkowski wrote the Shared Memory driver, and Bruce O'Neel wrote the drivers for accessing FITS les 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 parsing algorithm that is used to do on-the- y ltering of FITS tables. This algorithm essentially pre-compiles the user-supplied selection expression into a form that can be rapidly evaluated for eachrow. 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 e ort also bene tted from a much earlier lexical parsing routine that was developed byKentBlackburn (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 ltering or binning input FITS les 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 le 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 havemade valuable contributions to the development of CFITSIO. These include (with apologies to others that mayhave inadvertently been omitted): Steve Allen, Carl Akerlof, Keith Arnaud, Morten Krabbe Barfoed, Kent Blackburn, G Bodammer, RomkeBontekoe, Lucio Chiappetti, Keith Costorf, Robin Corbet, John Davis, Richard Fink, Ning Gan, Emily Greene, Gretchen Green, Joe Harrington, Cheng Ho, Phil Hodge, Jim Ingham, Yoshitaka 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, Je 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 Walton, 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 les. Users should refer to the documentation available from the NOST, as described in the introduction, for more detailed information on FITS formats. FITS was rst 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 le consists of one or more Header + Data Units (HDUs), where the rst 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 di erent primary datatypes are supported: Unsigned 8-bit bytes, 16 and 32-bit signed integers, and 32 and 64-bit oating 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 arraycontaining 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 de ned by the FITS standard: Image Extension - a N-dimensional array of pixels, like in a primary array ASCII Table Extension - rows and columns of data in ASCII character format 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. Anyunused space is padded with ll characters (ASCII blanks or NULs depending on the type of unit). Each Header Unit consists of anynumber of 80-character keyword records or `card images' (reminiscent of the 80-column punched cards whichwere prevalent when the FITS standard was developed) whichhave 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 byan 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 oating point number, a character string (enclosed in single quotes), or a boolean value (the letter T or F). A keyword may also haveanull or unde ned value if there is no speci ed value string, as in the second example. The last keyword in the header is always the `END' keyword which has no value or comment elds. There are manyrules 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 HISTORYkeywords are also frequently added to further document the data le. 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 le, 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: BITPIX { de nes the datatype of the array: 8, 16, 32, -32, -64 for unsigned 8{bit byte, 16{bit integer, 32{bit integer, 32{bit IEEE oating point, and 64{bit IEEE double precision oating point, respectively. NAXIS { the number of dimensions in the array, usually 0, 1, 2, 3, or 4. NAXISn { (n ranges from 1 to NAXIS) de nes 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: TFIELDS { number of elds or columns in the table NAXIS2 { number of rows in the table TTYPEn { for each column (n ranges from 1 to TFIELDS) gives the name of the column TFORMn { the datatype of the column 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 le to be opened or created that includes the following features: CFITSIO can read IRAF format images which have header le names that end with the '.imh' extension, as well as reading and writing FITS les, This feature is implemented in CFITSIO by rst converting the IRAF image into a temporary FITS format le in memory, then opening the FITS le. Any of the usual CFITSIO routines then may be used to read the image header or data. FITS les on the internet can be read (and sometimes written) using the FTP, HTTP, or ROOT protocols. FITS les can be piped between tasks on the stdin and stdout streams. FITS les can be read and written in shared memory. This can potentially achievemuch better data I/O performance compared to reading and writing the same FITS les on magnetic disk. Compressed FITS les in gzip or Unix COMPRESS format can be directly read. FITS table columns can be created, modi ed, or deleted 'on-the- y' as the table is opened by CFITSIO. This creates a virtual FITS le containing the modi cations that is then opened by the application program. Table rows may be selected, or ltered out, on the y when the table is opened by CFITSIO, based on an arbitrary user-speci ed 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. Histogram images may be created on the y 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 les. For example, these features transform a very simple program that just copies an input FITS le to a new output le (like the ` tscopy' program that is distributed with CFITSIO) into a multipurpose FITS le processing tool. By appending fairly simple quali ers onto the name of the input FITS le, the user can perform quite complex table editing operations (e.g., create new columns, or lter 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 le names in the next section, here are a few examples of FITS le names that giveaquickoverview of the allowed syntax:
'myfile.fits'

: the simplest case of a FITS le on disk in the current directory.

'myfile.imh': op ens an IRAF format image le and converts it on the y into a temp orary FITS format image in memory which can then be read with any other CFITSIO routine. 'myfile.fits.gz events, 2]': '-':

opens and uncompresses the le my le. ts then moves to the extension which has the keywords EXTNAME = 'EVENTS' and EXTVER = 2. a dash (minus sign) signi es that the input le is to be read from the stdin le stream, or that the output le is to be written to the stdout stream.
'ftp://legacy.gsfc.nasa.gov/test/vela.fits'

: FITS les in any ftp archive site on the internet may be directly opened with read-only access.
'http://legacy.gsfc.nasa.gov/software/test.fits'

the Web may be opened with read-only access.

: any valid URL to a FITS le on

similar to ftp access except that it provides write as well as read access to the les across the network. This uses the root protocol developed at CERN.
'shmem://h2 events]'

'root://legacy.gsfc.nasa.gov/test/vela.fits':

EVENTS extension.
'mem://'

: opens the FITS le in a shared memory segment and moves to the

: creates a scratch output le in core computer memory. The resulting ' le' 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 le.
'myfile.fits 3 Images(10)]': op ens 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 le. The application just sees this single image as the primary array. '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
'myfile.fits EVENTS] col Rad = sqrt(X**2 + Y**2)]'

15

: creates and opens a temporary le on the y (in memory or on disk) that is identical to my le. ts 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. 'myfile.fits EVENTS] PHA > 5]': creates and op ens a temp orary FITS les that is identical to 'my le. ts' except that the EVENTS table will only contain the rows that havevalues of the PHA column greater than 5. In general, any arbitrary boolean expression using a C or Fortran-likesyntax, whichmaycombine AND and OR operators, may be used to select rows from a table. 'myfile.fits EVENTS] bin (X,Y)=1,2048,4]': creates a temp orary FITS primary array image which is computed on the y 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. The nal 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 le 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 nally (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 nal 2-D image in the primary array of the opened le.

4.2 Detailed Filename Syntax
This section describes the full syntax for the CFITSIO FITS le 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 letype, 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 speci ers may follow in any order. Regardless of the order, however, the colFilter speci er, if present, will be processed rst by CFITSIO, followed by the rowFilter speci er, and nally by the binSpec speci er.

4.2.1 Filetype
The type of le determines the medium on which the le is located (e.g., disk or network) and, hence, which internal device driver is used by CFITSIO to read and/or write the le. Currently supported types are
file:// ftp:// - file on local magnetic disk (default) - 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 letype is not speci ed, then type le:// is assumed. The double slashes '//' are optional and may be omitted in most cases.

Notes about the root letype
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 modi ed version which supports a command to return the length of the le. This modi ed 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 les 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 le with "kill -HUP ". 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 -p port# -d level says we were started by inetd specifies a different port to listen on level of debug info written to syslog 0 = no debug (default) 1 = minimum 2 = medium 3 = maximum

Rootd can also be con gured 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
mkdir /var/spool/rootd mkdir /var/spool/rootd/tmp chmod 777 /var/spool/rootd/tmp

CHAPTER 4. EXTENDED FILE NAME SYNTAX

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 le tree is set to the rootd home directory, therefore only les below the home directory can be accessed. Anonymous mode only works when the server is started via inetd.

Notes about the shmem letype:
Shared memory les 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 les in CFITSIO by calling:
fit_create_file(&fitsfileptr, "shmem://h2", &status)

where the root ` le' names are currently restricted to be 'h0', 'h1', 'h2', 'h3', etc., up to a maximumn number de ned 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 havefewer restrictions on the number of les and on their names, is planned for the future. When opening an already existing FITS le in shared memory one calls the usual CFITSIO routine:
fits_open_file(&fitsfileptr, "shmem://h7", mode, &status)

The le mode can be READWRITE or READONLY just as with disk les. More than one process can operate on READONLY mode les at the same time. CFITSIO supports proper lelocking (both in READONLY and READWRITE modes), so calls to ts open le maybe locked out until another other process closes the le. When an application is nished accessing a FITS le in a shared memory segment, it may close it (and the le will remain in the system) with ts close le, or delete it with ts delete le. Physical deletion is postponed until the last process calls clos/ delt. ts delete le tries to obtain a


4.2. DETAILED FILENAME SYNTAX

19

READWRITE lock on the le to be deleted, thus it can be blocked if the ob ject was not opened in READWRITE mode. A shared memory management utility program called `smem', is included with the CFITSIO distribution. It can be built bytyping `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 ob jects, run the system utility program `ipcs -a]'.

4.2.2 Base Filename
The base lename is the name of the le optionally including the director/subdirectory path, and in the case of `ftp', `http', and `root' letypes, the machine identi er. Examples:
myfile.fits !data.fits /data/myfile.fits fits.gsfc.nasa.gov/ftp/sampledata/myfile.fits.gz

When creating a new output le on magnetic disk (of type le://) if the base lename begins with an exclamation point (!) then any existing le with that same basename will be deleted prior to creating the new FITS le. Otherwise if the le to be created already exists, then CFITSIO will return an error and will not overwrite the existing le. 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 le may be compressed with the gzip or Unix compress algorithms, in which case CFITSIO will uncompress the le on the y into a temporary le (in memory or on disk). Compressed les may only be opened with read-only permission. When specifying the name of a compressed FITS le it is not necessary to append the le su x (e.g., '.gz' or '.Z'). If CFITSIO cannot nd the input le name without the su x, then it will automatically search for a compressed le with the same root name. In the case of reading ftp and http type les, CFITSIO generally looks for a compressed version of the le rst, before trying to open the uncompressed le. By default, CFITSIO copies (and uncompressed if necessary) the ftp or http FITS le 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 le, so in this case, the output lename speci er (see the next section) can be used to further control how CFITSIO reads ftp and http les. One special case is where the lename = '-' (a dash or minus sign), which signi es that the input le is to be read from the stdin stream, or written to the stdout stream if a new output le is being created. In the case of reading from stdin, CFITSIO rst copies the whole stream into a temporary FITS le (in memory or on disk), and subsequent reading of the FITS le occurs in this copy. When writing to stdout, CFITSIO rst constructs the whole le in memory (since random access is required), then ushes it out to the stdout stream when the le is closed. This feature allows FITS les to be piped between tasks in memory rather than having to create temporary


20

CHAPTER 4. EXTENDED FILE NAME SYNTAX

intermediate FITS les on disk. For example if task1 creates an output FITS le, and task2 reads an input FITS le, the FITS le 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 le o of the command line. When specifying the name of the new FITS le to be created by ts create le, if the name is preceded with an exclamation mark (!), then any existing le with the same name will be clobbered, or overwritten, by the newly created le. Otherwise, CFITSIO will return an error if the le to be created already exists.

4.2.3 Output File Name when Opening an Existing File
An optional output lename may be speci ed in parentheses immediately following base le name to be opened. In a number of instances CFITSIO will create a temporary copy in memory of the input FITS le before it is opened and passed to the application program. This happens by default when opening a network FTP or HTTP-type le, when reading a compressed FITS le on a local disk, when reading from the stdin stream, or when a column lter, row lter, or binning speci er is included as part of the input le speci cation. If there is not enough memory to create the le copy, then CFITSIO will exit with an error. In these cases one can force a permanent le to be created on disk, instead of a temporary le in memory,by supplying the name in parentheses immediately following the base le name. The output lename can include the ' !' clobber ag. Thus, if the input lename to CFITSIO is:
file1.fits.gz(file2.fits)

then CFITSIO will uncompress ` le1. ts.gz' into the local disk le ` le2. ts' before opening it. CFITSIO does not automatically delete the output le, so it will still exist after the application program exits. In some cases, several di erent temporary FITS les will be created in sequence, for instance, if one opens a remote le using FTP, then lters rows in a binary table extension, then create an image by binning a pair of columns. In this case, the remote le will be copied to a temporary local le, then a second temporary le will be created containing the ltered rows of the table, and nally a third temporary le containing the binned image will be created. In cases like this where multiple les are created, the out le speci er will be interpreted the name of the nal le as described below, in descending priority: as the name of the nal image le if an image within a single binary table cell is opened or if an image is created by binning a table column. as the name of the le containing the ltered table if a column lter and/or a row lter are speci ed.


4.2. DETAILED FILENAME SYNTAX

21

as the name of the local copy of the remote FTP or HTTP le. as the name of the uncompressed version of the FITS le, if a compressed FITS le on local disk has been opened. otherwise, the output lename is ignored. The output le speci er is useful when reading FTP or HTTP-type FITS les since it can be used to create a local disk copy of the le that can be reused in the future. If the output le name = `*' then a local le with the same name as the network le will be created. Note that CFITSIO will behave di erently depending on whether the remote le is compressed or not as shown by the following examples: `ftp://remote.machine/tmp/my le. ts.gz(*)' - the remote compressed le is copied to the local compressed le `my le. ts.gz', which is then uncompressed in local memory before being opened and passed to the application program. `ftp://remote.machine/tmp/my le. ts.gz(my le. ts)' - the remote compressed le is copied and uncompressed into the local le `my le. ts'. This example requires less local memory than the previous example since the le is uncompressed on disk instead of in memory. `ftp://remote.machine/tmp/my le. ts(my le. ts.gz)' - this will usually produce an error since CFITSIO itself cannot compress les. 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 con gured. In some cases, if the le `my le. ts.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 le if only the uncompressed version exists. This can get rather confusing, so users should use a certain amount of caution when using the output le speci er with FTP or HTTP le 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 le is created with a call to ts create le, the name of a template le may be supplied in parentheses immediately following the name of the new le to be created. This template is used to de ne the structure of one or more HDUs in the new le. The template le may be another FITS le, in which case the newly created le will have exactly the same keywords in each HDU as in the template FITS le, but all the data units will be lled with zeros. The template le may also be an ASCII text le, where each line (in general) describes one FITS keyword record. The format of the ASCII template le 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 de nitions. 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 le itself. The format of each template line follows very closely the format of the FITS keyword record:
KEYWORD = KEYVALUE / COMMENT

All the elds are optional, and only one eld of each type per record is allowed. The elds must appear in order. The result of parsing is one (or possibly more, in the case of a long keyvalue eld) 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 eld is order dependent but position independent, except if the rst 8 characters of a record are blanks then the entire line is treated as a FITS commentkeyword (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 eld 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 bythe "=" character with optional spaces allowed on either side of the "=". KEYVALUE elds 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 unde ned (null) value is speci ed if the template record only contains blanks between the "=" and the "/" comment eld delimiter. Keyword values longer than 68 characters (for string data type) are permitted string convention. They can either be speci ed as a single "long" line, or by 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

in single quotes. An following the "=" or using the c tsio long using multiple lines

The format of template lines with CONTINUE keyword is very strict: 3spacesmust follow CONTINUE and the rest of the line is copied verbatim to the FITS le.


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 eld must be preceeded by "/", which is used to separate it from the keyword value eld. Exceptions are if the KEYWORD eld contains COMMENT, HISTORY, CONTINUE, or if the rst 8 chars of the record are blanks.

Template Parser Directives
The template parser recognizes 3 special keywords (directives): -must be followed by a lename. Forces parser to temporarily stop reading current le and begin reading the include le. Once the parser reaches the end of the include le it continues with the current one. Include les can be nested. HDU de nitions can span multiple les.
\include \group \end

- marks beginning of GROUP de nition

- marks end of GROUP de nition

Formal Template Syntax
TEMPLATE = BLOCK BLOCK ... ] BLOCK = { HDU | GROUP } GROUP = \GROUP HDU = XTENSION LINE = KEYWORD BLOCK ... ] \END LINE ... ] { XTENSION | \GROUP | \END | EOF } =]] 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 de nes 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 le HDUs. The start of an HDU de nition is denoted with a template line containing either of the following keywords: 'SIMPLE' : begins a Primary array (PHDU) de nition. One per template is allowed and only as a rst keyword in the template le. If not present then an empty PHDU is created (of size 2880 bytes) and the rst HDU de ned in template les is saved as a 2nd HDU ( rst after dummy one).


24

CHAPTER 4. EXTENDED FILE NAME SYNTAX

'XTENSION' : begins any xtension HDU de nition. The end of an HDU de nition is given by the next occurance of an 'XTENSION' keyword, a group or end directive, or the end of the template le. The start of a GROUP de nition is denoted with the group directive, and the end of a GROUP de nition 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 de nition itself occupies one FITS le HDU of special type (GROUP HDU), so if a template speci es 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 le 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 de ne 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 le using the group directives, look at the sample.tpl le 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 rst keyword eld encountered in a given HDU de nition ending with '#' is used as the index value incrementor. Each time this keyword eld (also ending with '#') is encountered in the header de nition the index value is incremented by1. All keyword elds ending with '#' encountered between index value incrementor keyword elds 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 DUMMY PARAM# Resulting keyword (in GROUP HDU add 6) DUMMY PARAM1


4.2. DETAILED FILENAME SYNTAX
DUMMY# PARAM PARAM# TEST# PARAM# TEST# DUMMY1 PARAM PARAM2 TEST2 PARAM3 TEST3

25

The index value and index value incrementor keyword eld are reset to 1 for each HDU or to 7 for each GROUP de ned in the template.

Errors
In general ts 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, ts 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 le and it will return with an error.

4.2.5 HDU Location Speci cation
The optional HDU location speci er de nes which HDU (Header-Data Unit, also known as an `extension') within the FITS le to initially open. It must immediately follow the base le name (or the output le name if present). If it is not speci ed then the rst HDU (the primary array) is opened. The HDU location speci er is required if the colFilter, rowFilter, or binSpec speci ers are present, because the primary array is not a valid HDU for these operations. The HDU maybe speci ed 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 speci ed, as described below. The absolute position of the extension is speci ed either by enclosed the number in square brackets (e.g., `1]' = the rst 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 speci ed, then the rst 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 speci er is equal to `PRIMARY]' or `P]', then the primary array (the rst 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 rowofthe vector column contains a di erent image). Such an image can be opened with CFITSIO by specifying the desired column name and the row number after the binary table HDU speci er as shown in the following


26

CHAPTER 4. EXTENDED FILE NAME SYNTAX

examples. The column name is separated from the HDU speci er 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 speci ed either by giving an absolute integer rownumber (starting with 1 for the rst row), or by specifying a boolean expression that evaluates to TRUE for the desired row. The rst row that satis es the expression will be used. The row selection expression has the same syntax as described in the Row Filter Speci er 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 speci ed, 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 speci ed before the image section speci er. 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
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.

27

When CFITSIO opens an image section it rst creates a temporary le containing the image section plus a copy of any other HDUs in the le. This temporary le is then opened by the application program, so it is not possible to write to or modify the input le 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 Speci cation
The optional column/keyword ltering speci er is used to modify the column structure and/or the header keywords in the HDU that was selected with the previous HDU location speci er. This ltering speci er must be enclosed in square brackets and can be distinguished from a general row lter speci er (described below) by the fact that it begins with the string 'col ' and is not immediately followed by an equals sign. The original le is not changed by this ltering operation, and instead the modi cations are made on a copy of the input FITS le (usually in memory), which also contains a copy of all the other HDUs in the le. This temporary le is passed to the application program and will persist only until the le is closed or until the program exits, unless the out le speci er (see above) is also supplied. The column/keyword lter can be used to perform the following operations. More than one operation may be speci ed by separating them with semi-colons. 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. 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. 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' lled with zeros). The datatype is speci ed 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 speci ed then an appropriate datatype will be chosen depending on the form of the expression (maybe 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 speci ed.


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 speci ed in parentheses immediately following the keyword name (instead of supplying a datatype as in the case of creating a new column). 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 lter speci cation section. For complex or commonly used operations, one can also place the operations into a text le and import it into the column lter using the syntax 'col @ lename.txt]'. The operations can extend over multiple lines of the le, 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' - creates new PI column from PHA values - recomputes the rate column by dividing it by the EXPOSURE keyword value.

col PI=PHA * 1.1 + 0.2] col rate = rate/exposure]

4.2.8 Row Filtering Speci cation
The optional row lter is a boolean expression enclosed in square brackets for ltering or selecting rows from the input FITS table. A new FITS le 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 le are also copied to the new le). The original FITS le is closed and the new le is opened and passed to the application program. The new le will persist only until the le is closed or until the program exits, unless the output le speci er (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 speci ed 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 o set within curly braces. For example, 'PHA-3' will evaluate to the value of column PHA, 3 rows abovethe row currently being processed. One cannot specify an absolute rownumber, only a relative o set. Rows that fall outside the table will be treated as unde ned, 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. "less than" .lt. "greater than" .gt. "or" .or. "negation" .not. .EQ. == .LT. < .GT. > .OR. || .NOT. ! "not equal" .ne. "less than/equal" .le. "greater than/equal" .ge. "and" .and. "approx. equal(1e-7)" ~ .NE. .LE. .GE. .AND. != <= =< >= => &&

Note that the exclamation point, ' !', is a special UNIX character, so line rather than entered at a task prompt, it must be preceded by a shell to ignore it. The expression may also include arithmetic operators and functions. radians, not degrees. The following arithmetic operators and functions (function names are case insensitive):
"addition" "multiplication" "negation" "absolute value" "sine" "arc cosine" "arc tangent" "exponential" "natural log" "modulus" "minimum" + * abs(x) sin(x) arccos(x) arctan(x) exp(x) log(x) i%j min(x,y) "subtraction" "division" "exponentiation" "cosine" "tangent" "arc sine" "arc tangent" "square root" "common log" "random # 0.0,1.0)" "maximum"

if it is used on the command backslash to force the UNIX Trigonometric functions use can be used in the expression
/ ** ^ cos(x) tan(x) arcsin(x) arctan2(x,y) sqrt(x) log10(x) random() 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 elementcontained 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 (5 3) equals 7 whereas 7 (5 3) equals 0. There are three functions that are primarily for use with SAO region les 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 twovalues are close to each other, i.e., if they are "near" each other to within a user speci ed tolerance. The arguments, value 1and value 2can be integer or real and represent the two values who's proximity is being tested to be within the speci ed tolerance, also an integer or real:
near(value_1, value_2, tolerance)

When a NULL, or unde ned, value is encountered in the FITS table, the expression will evaluate to NULL unless the unde ned 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 "de nes" 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" "integer to real" (int) x (float) i (INT) x (FLOAT) i

Bit masks can be used to select out rows from bit columns (TFORMn = #X) in FITS les. To represent the mask, binary, octal, and hex formats are allowed:


4.2. DETAILED FILENAME SYNTAX
binary: octal: hex: b0110xx1010000101xxxx0001 o720x1 -> (b111010000xxx001) h0FxD -> (b00001111xxxx1101)

31

In all the representations, an xorXis allowed in the mask as a wild card. Note that the x represents a di erentnumber 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 ags 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 It is not necessary to specify the leading (most signi cant) zero the second expression above. Bit wise AND, OR and NOT operations are also possible on '&'(AND), 'j'(OR), and the ' !'(NOT) operators. All of these op can then be used with the equal operator. For example:

compared. (0) bits in the mask, as shown in two or more bit elds using the erators result in a bit eld which

(!flags) == b1101100 (flags & b1000001) == bx000001

Bit elds 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 #deg 3.1415... #pi/180 #e #row 2.7182... current row number

A string constantmust 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. Twovectors 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 elementby element basis. Comparing two vector columns, eg "COL1 == COL2", thus results in another vector of boolean values indicating which elements of the twovectors 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 whichyou wanted to select the 57th component for use in the expression, then PHAS57] 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 elementof eachrow is accessed by ARRAY4D1,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 whichcontain 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 speci ed with the syntax ARRAY4D4]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 ARRAY4D4]. 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 ltering method applied to FITS les is a time lter using a Good Time Interval (GTI) extension. A high-level function, gti lter(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 lename, if speci ed, can be blank ("") which will mean to use the rst extension with the name "*GTI*" in the current le, a plain extension speci er (eg, "+2", "2]", or "STDGTI]") which will be used to select an extension in the current le, or a regular lename with or without an extension speci er which in the latter case will mean to use the rst 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 speci ed, they both must be. Note that the quotes surrounding the lename and START/STOP column names are required. In its simplest form, no parameters need to be provided { default values will be used. The expression "gti lter()" is equivalentto
gtifilter( "", TIME, "*START*", "*STOP*" )

This will search the current le for a GTI extension, lter 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 slightvariations in naming conventions such as "TSTART" or "STARTTIME". The same default values apply for unspeci ed parameters when the rst one or two parameters are speci ed. The function automatically searches for TIMEZERO/I/F keywords in the current and GTI extensions, applying a relative time o set, if necessary. Another common ltering method is a spatial lter using a SAO- style region le. The syntax for this high-level lter is
regfilter( "regfilename" , Xexpr, Yexpr , "wcs cols" ] ] )

The region le name is required, but the rest is optional. Without any explicit expression for the X and Y coordinates (in pixels), the lter will search for and operate on columns "X" and "Y". If the region le is in "degrees" format instead of "pixels" ("hhmmss" format is not supported, yet), the lter will need WCS information to convert the region coordinates to pixels. If supplied, the nal parameter string contains the names of the 2 columns (space or comma separated) which contain the desired WCS information. If not supplied, the lter 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
Point Line Polygon Rectangle Box Diamond Circle Annulus Ellipse Elliptannulus Sector ( ( ( ( ( ( ( ( ( ( ( X1, X1, X1, X1, Xc, Xc, Xc, Xc, Xc, Xc, Xc, Y1 ) Y1, Y1, Y1, Yc, Yc, Yc, Yc, Yc, Yc, Yc,

CHAPTER 4. EXTENDED FILE NAME SYNTAX
<- One pixel square region X2, Y2 ) <- One pixel wide region X2, Y2, ... ) <- Rest are interiors with X2, Y2, A ) | boundaries considered Wdth, Hght, A ) V within the region Wdth, Hght, A ) R) Rin, Rout ) Rx, Ry, A ) Rinx, Riny, Routx, Routy, Ain, Aout ) 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 semima jor/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 o , 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 de ned region is instead the area *outside* its boundary (ie, the region is inverted). All the shapes within a single region le are AND'd together to create the region. For complex or commonly used lters, one can also place the expression into a text le and import it into the row lter using the syntax '@ lename.txt]'. The expression can be arbitrarily complex and extend over multiple lines of the le. 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) - Extract row numbers 125 through 175 - Extract all rows that have the (4,5) component of the IMAGE column greater than 100

#row >= 125 && #row <= 175] IMAGE 4,5] .gt. 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
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. - Extract rows using the expression contained within the text file rowFilter.txt

35

@rowFilter.txt]

4.2.9 Binning or Histogramming Speci cation
The optional binning speci er is enclosed in square brackets and can be distinguished from a general row lter speci cation by the fact that it begins with the keyword 'bin' not immediately followed by an equals sign. When binning is spec ed, a temporary N-dimensional FITS primary array is created by computing the histogram of the values in the speci ed columns of a FITS table extension. After the histogram is computed the input FITS le 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 le (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 speci ed by appending 'b' (for 8-bit byte), 'i' (for 16-bit integers), 'j' (for 32-bit integer), 'r' (for 32-bit oating points), or 'd' (for 64-bit double precision oating point) to the 'bin' keyword (e.g. 'binr X]' creates a real oating point image). If the datatype is not explicitly speci ed then a 32-bit integer image will be created by default, unless the weighting option is also speci ed in which case the image will have a 32-bit oating point data type by default. The histogram image mayhave from 1 to 4 dimensions (axes), depending on the number of columns that are speci ed. The general form of the binning speci cation 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 maybe given instead of the name, preceded by a pound sign (e.g., bin #4=1:512]). If the column name is not speci ed, then CFITSIO will rst try to use the 'preferred column' as speci ed 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 oating pointnumbers, 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 = bin x = bin x = bin x = bin x = bin x = bin x] bin 4] bin] :512:2] 1::2] 1:512] 1:] :512] 2] use default use default use default use default use default use default use default default 2-D default 2-D minimum value maximum value bin size maximum value and bin size minimum value and bin size minimum and maximum values minimum, maximum and bin size image, bin size = 4 in both axes 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 valuesinthe 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 speci cation. In this case all the column names may be listed within parentheses, followed by the (single) binning speci cation, as in:
bin (X,Y)=1:512:2] bin (X,Y) = 5]

The optional weighting factor is the last item in the binning speci er 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 speci ed, then the default weight = 1 is assumed. The weighting factor may be a constantinteger or oating pointnumber, 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 rowbyrow 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 le and import it into the binning speci cation using the syntax 'binbijrd @ lename.txt]'. The le's contents can extend over multiple lines, although it must still conform to the no-spaces rule for the min:max:binsize syntax and each axis speci cation must still be comma-separated. Examples:


4.2. DETAILED FILENAME SYNTAX
bini detx, dety] - 2-D, 16-bit integer histogram of DETX and DETY columns, using default values for the histogram range and binsize /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. - 1-D lightcurve, range determined by the TSTART and TSTOP keywords, with 0.1 unit size bins. - 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. - Use the contents of the text file binFilter.txt for the binning specifications.

37

bin (detx, dety)=16

bin time=TSTART:TSTOP:0.1]

bin pha, time=8000.:8100.:0.1]

bin @binFilter.txt]


38

CHAPTER 4. EXTENDED FILE NAME SYNTAX


Chapter 5

CFITSIO Conventions and Guidelines
5.1 CFITSIO De nitions
Any program that uses the CFITSIO interface must include the tsio.h header le with the statement
#include "fitsio.h"

This header le contains the prototypes for all the CFITSIO user interface routines as well as the de nitions of various constants used in the interface. It also de nes a C structure of type ` ts le' that is used by CFITSIO to store the relevant parameters that de ne the format of a particular FITS le. Application programs must de ne a pointer to this structure for each FITS le that is to be opened. This structure is initialized (i.e., memory is allocated for the structure) when the FITS le is rst opened or created with the ts open le or ts create le routines. This ts le pointer is then passed as the rst argument to every other CFITSIO routine that operates on the FITS le. Application programs must not directly read or write elements in this ts le structure because the de nition of the structure maychange in future versions of CFITSIO. A number of symbolic constants are also de ned in tsio.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 #define #define #define #define #define #define FLEN_FILENAME 1025 /* max length of a filename */ FLEN_KEYWORD 72 /* max length of a keyword */ FLEN_CARD 81 /* max length of a FITS header card */ FLEN_VALUE 71 /* max length of a keyword value string */ FLEN_COMMENT 73 /* max length of a keyword comment string */ FLEN_ERRMSG 81 /* max length of a CFITSIO error message */ 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 #define #define #define #define BYTE_IMG SHORT_IMG LONG_IMG FLOAT_IMG DOUBLE_IMG 8 16 32 -32 -64 /* /* /* /* /* 8-bit unsigned integers */ 16-bit signed integers */ 32-bit signed integers */ 32-bit single precision floating point */ 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 #define TBIT #define TBYTE #define TLOGICAL #define #define #define #define #define #define #define 1 11 14 /* /* /* /* /* /* /* /* /* /* /* TFORM CODE 'X' */ 8-bit unsigned byte, 'B' */ logicals (int for keywords */ and char for table cols 'L' */ ASCII string, 'A' */ signed short, 'I' */ signed long, 'J' */ single precision float, 'E' */ double precision float, 'D' */ complex (pair of floats) 'C' */ double complex (2 doubles) 'M' */

TSTRING 16 TSHORT 21 TLONG 41 TFLOAT 42 TDOUBLE 82 TCOMPLEX 83 TDBLCOMPLEX 163

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
HDU type code values (value returned when moving to new HDU): #define #define #define #define IMAGE_HDU 0 ASCII_TBL 1 BINARY_TBL 2 ANY_HDU -1 /* /* /* /* Primary Array or ASCII table HDU Binary table HDU matches any type IMAGE HDU */ */ */ of HDU */

41

Column name and string matching case-sensitivity: #define CASESEN 1 #define CASEINSEN 0 /* do case-sensitive string match */ /* 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 les that it reads or writes. There is no internal limit on the size of the dimensions of the primary arrayor 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, whichmay a ect some extreme cases: 1. The maximum number of les that may be simultaneously opened is limited to the number of internal IO bu ers allocated in CFITSIO (currently 25, as de ned by NIOBUF in the le tsio2.h), or by the limit of the underlying C compiler or machine operating system, which ever is smaller. The C symbolic constantFOPEN MAX usually de nes the total number of les that mayopen at once (this includes any other text or binary les whichmay be open, not just FITS les). 2. The maximum number of extensions that can be read or written in a single FITS le is currently set to 1000 as de ned by MAXHDU in the tsio.h le. This value may be increased if necessary, but the access times to the later extensions in such les maybecomevery long. 3. CFITSIO can handle FITS les 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 les, 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 le. Thus, one can open the same FITS le twice within a single program and move to 2 di erent HDUs in the le, and then read and write data or keywords to the 2 extensions just as if one were accessing 2 completely separate FITS les. Since in general it is not possible to physically open the same le twice and then expect to be able to simultaneously (or in alternating succession) write to 2 di erent locations in the le, CFITSIO recognizes when the le to be opened (in the call to ts open le) has already been opened and instead of actually opening the le again, just logically links the new le to the old le. (This only applies if the le is opened more than once within the same program, and does not prevent the same le from being simultaneously opened by more than one program). Then before CFITSIO reads or writes to either (logical) le, it makes sure that any modi cations made to the other le have been completely ushed from the internal bu ers to the le. Thus, in principle, one could open a le twice, in one case pointing to the rst 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 le, There may be some e ciency penalties in doing this however, since CFITSIO has to ush all the internal bu ers related to one le 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 di erent HDUs in the same le.

5.4 Current Header Data Unit (CHDU)
In general, a FITS le 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 le is rst created or opened the CHDU is automatically de ned to be the rst HDU (i.e., the primary array). CFITSIO routines are provided to move to and open any other existing HDU within the FITS le or to append or insert a new HDU in the FITS le 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 di er only in the datatype of the associated parameter(s). The datatype of these routines is indicated by the su x of the routine name. The short routine names havea 1 or 2 character su x (e.g., 'j' in ' pkyj') while the long routine names have a 4 character or longer su x as shown in the following table:
Long Names Short Names Data Type


5.5. FUNCTION NAMES AND DATATYPES
--------_bit x _byt b _sht i _lng j _usht ui _ulng uj _uint uk _int k _flt e _fixflt f _dbl d _fixdbl g _cmp c _fixcmp fc _dblcmp m _fixdblcmp fm _log l _str s ---bit unsigned byte short integer long integer unsigned short integer unsigned long integer unsigned int integer int integer real exponential floating point (float) real fixed-decimal format floating point (float) double precision real floating-point (double) double precision fixed-format floating point (double) complex reals (pairs of float values) complex reals, fixed-format floating point double precision complex (pairs of double values) double precision complex, fixed-format floating point logical (int) character string

43

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 anynumerical data type a returned value = 0 indicates false, and any other value = true. The `int' datatype maybe 2 bytes long on some IBM PC compatible systems and is usually 4 bytes long on most other systems. Some 64-bit machines, however, likethe Dec Alpha/OSF, de ne 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 and8bytes when reading or writing `long' integers on Alpha/OSF systems. When dealing with the FITS byte datatype it is importanttoremember that the rawvalues (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 de ne a 'char' variable as signed, so it is important to explicitly declare a numeric char variable as 'unsigned char' to avoid anyambiguity 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 e cient 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 oat or double values, respectively, where the rst 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 e ciently store unsigned integer data values in images and binary tables. The convention used in FITS les is to store the unsigned integers as signed integers with an associated o set (speci ed by the BZERO or TZEROn keyword). For example, to store unsigned 16-bit integer values in a FITS image the image would be de ned 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 o set 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 e ciently and transparently apply the appropriate o set 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 le. As a convenience for users, CFITSIO has several prede ned 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 les 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 ts 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 ts write img routine writes the array of unsigned short integers (uarray) into the primary array of the FITS le. Similarly, a 32-bit unsigned integer image may be created by setting the second parameter in ts create img equal to `ULONG IMG' and by calling the ts 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 de nes the format of a column, CFITSIO recognized 2 additional datatype codes besides those already de ned 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 le 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" /* define the char *ttype ] char *tform ] char *tunit ] ... /* extension name */

name, datatype, and physical units for the 2 columns */ = { "Col_1", "Col_2" } = { "1U", "1V" } /* special CFITSIO codes */ = { " ", "" }

/* 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 ts 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-signi cant space characters (ASCII 32) to ll up the header record or the column width. When reading a FITS string value, the CFITSIO routines will strip o these non-signi cant trailing spaces and will return a null-terminated string value containing only the signi cant characters. Leading spaces in a FITS string are considered signi cant. If the string contains all blanks, then CFITSIO will return a single blank character, i.e, the rst blank is considered to be signi cant, since it distinquishes the string from a null or unde ned string, but the remaining trailing spaces are not signi cant. Similarly, when writing string values to a FITS le the CFITSIO routines expect to get a nullterminated string as input CFITSIO will pad the string with blanks if necessary when writing it to the FITS le. 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 incorrectly. This type of error can be di cult to debug, so programmers should always ensure that the char arrays are allocated enough space to hold the longest possible string, including the terminating NULL character. The tsio.h le contains the following de ned constants which programmers are strongly encouraged to use whenever they are allocating space for char arrays:
#define #define #define #define #define #define #define FLEN_FILENAME 1025 /* max length of a filename */ FLEN_KEYWORD 72 /* max length of a keyword */ FLEN_CARD 81 /* length of a FITS header card */ FLEN_VALUE 71 /* max length of a keyword value string */ FLEN_COMMENT 73 /* max length of a keyword comment string */ FLEN_ERRMSG 81 /* max length of a CFITSIO error message */ 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 conversion. 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 le. 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 oating pointscaledvalue is truncated to an integer (not rounded to the nearest integer). The ts set bscale and ts set tscale routines (described in the `Advanced' chapter) may be used to override the scaling parameters de ned in the header (e.g., to turn o the scaling so that the program can read the raw unscaled values from the FITS le). When writing numerical data to the primary array or to a table column the data values will generally be automatically inversely scaled bythe 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 e ect. One may also use the ts set bscale and ts set tscale routines to de ne or override the scaling keywords in the header (e.g., to turn o the scaling so that the program can write the raw unscaled values into the FITS le). If scaling is performed, the inverse scaled output value that is written into the FITS le 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 le.

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

exibility 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 (de ned in tsio.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 ts report error will print out the entire error message stack, or alternatively one may call ts 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 elds 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 speci ed when the table is created (e.g., if the TFORM keyword value is simply speci ed 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 BINARYTABLES

49

The same routines which read and write data in an ordinary xed length binary table extension are also used for variable length elds, however, the routine parameters take on a slightly di erent interpretation as described below. All the data in a variable length eld is written into an area called the `heap' which follows the main xed-length FITS binary table. The size of the heap, in bytes, is speci ed bythe 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 anyfollowing HDUs do not get overwritten. By default the heap data area starts immediately after the last row of the xed-length table. This default starting location maybe 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 e cient 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 eld the entire arrayofvalues for a given row of the table must be written with a single call to ts write col. The total length of the arrayis given by nelements + rstelem - 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 eld should only be written once. An exception to this general rule occurs when setting elements of an array as unde ned. One must rst write a dummyvalue into the arraywith ts write col, and then call ts write col nul to ag the desired elements as unde ned. (Do not use the ts write colnul routines with variable length elds). Note that the rows of a table, whether xed 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 eld (e.g., TFORM = '1PA') only a single character string can be written. The ` rstelem' and `nelements' parameter values in the ts 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 ts write descript routine is useful in situations where multiple rows of a variable length column have the identical arrayofvalues. One can simply write the array once for the rst row, and then use ts 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 eld 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 xed length table eld. 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 ts read descript routine.


50

CHAPTER 5. CFITSIO CONVENTIONS AND GUIDELINES

5.12 Support for IEEE Special Values
The ANSI/IEEE-754 oating-pointnumber standard de nes certain special values that are used to represent such quantities as Not-a-Number (NaN), denormalized, under ow, over ow, and in nity. (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 oating point data in FITS les recognize these IEEE special values and by default interpret the over ow and in nityvalues as being equivalentto a NaN, and convert the under ow and denormalized values into zeros. In some cases programmers may want access to the raw IEEE values, without any modi cation by CFITSIO. This can be done by calling the ts read img or ts 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 modi cation. This is not fully supported on VAX/VMS machines, however, where there is no easy wayto 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 le. 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, suchas1. Then after all the data have been written and the true dimensions are known, then the NAXISn value should be updated using the ts update key routine before moving to another extension or closing the FITS le. When writing to FITS tables, CFITSIO automatically keeps track of the highest rownumber that is written to, and will increase the size of the table if necessary. CFITSIO will also automatically insert space in the FITS le 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 modi es 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 de ned in the o cial 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 les 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 t 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= STRKEY = CONTINUE CONTINUE 'OGIP 1.0' / The OGIP Long String Convention may be used. 'This is a very long string keyword&' / Optional Comment ' value that is continued over 3 keywords in the & ' '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 anysoftware that must read the keywords. A routine called ts 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 fits_insert_key_longstr fits_modify_key_longstr fits_update_key_longstr fits_read_key_longstr fits_delete_key write a insert a modify a modify a read a delete a long string keyword value long string keyword value long string keyword value long string keyword value long string keyword value keyword

The ts 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. Consequently, programs which use the ts 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 ( ts update key and ts write key) do not support this long string convention and only support strings up to 68 characters 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 ts 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 de nition of the FITS binary table extension format does not provide a simple way to specify that a character column contains an array of xed-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 ( xed) 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 de nition document speci es 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 de nition document that was approved bythe IAU in 1994 contains an appendix describing an alternate convention for specifying arrays of xed or variable length strings in a binary table character column (with the form 'rA:SSTRw/nnn)'. This appendix was not o cially voted on bythe IAU and hence is still provisional. CFITSIO does not currently support this proposal.

5.14.3 Keyword Units Strings
One de ciency of the current FITS Standard is that it does not de ne a speci c 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 eld of the keyword is often used for this purpose, but the units are usually not speci ed in a well de ned format that FITS readers can easily recognize and extract. Tosolve this de ciency, CFITSIO uses a local convention in whichthe keyword units are enclosed in square brackets as the rst token in the keyword comment eld more speci cally, the opening square bracket immediately follows the slash '/' comment eld 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
V_HELIO = 16.23 / km s**(-1)] heliocentric velocity LAMBDA = 5400. / angstrom] central wavelength FLUX = 4.9033487787637465E-30 / J/cm**2/s] average flux

53

In general, the units named tion that the preferred unit The ts read key unit and the keyword unit strings in

in the IAU(1988) Style Guide are recommended, with the main excepfor angle is 'deg' for degrees. ts write key unit routines in CFITSIO read and write, respectively, 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 suchas:
HIERARCH ESO INS FOCU POS = -0.00002500 / Focus position

Basically, this convention uses the FITS keyword 'HIERARCH' to indicate that this convention is being used, then the actual keyword name ('ESO INS FOCU POS' in this example) begins 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 comment elds 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 suchkeywords:
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 speci c implementation details of the HIERARCH convention. 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 rst 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 convention to write the keyword. The maximum keyword name length is 67 characters, which leaves only 1 space for the value eld. A more practical limit is about 40 characters, whichleaves 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 les. In order to achieve the best performance, however, application programmers must be careful to call the CFITSIO routines appropriately and in an e cient sequence inappropriate usage of CFITSIO routines can greatly slowdown 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 les can occur at even higher rates (30MB/s or more) if the FITS le is still cached in system memory following a previous read or write operation on the same le. 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 le. 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 le (e.g, reading a keyword, or writing a row in a table) it would be very ine cientto physically read or write such small blocks of data directly in the FITS le on disk, therefore CFITSIO maintains a set of internal Input{Output (IO) bu ers in RAM memory that each contain one FITS block (2880 bytes) of data. Whenever CFITSIO needs to access data in the FITS le, it rst transfers the FITS blockcontaining those bytes into one of the IO bu ers in memory. The next time CFITSIO needs to access bytes in the same block it can then go to the fast IO bu er rather than using a much slower system disk access routine. The number of available IO bu ers is determined by the NIOBUF parameter (in tsio2.h) and is currently set to 25. Whenever CFITSIO reads or writes data it rst checks to see if that block of the FITS le is already loaded into one of the IO bu ers. If not, and if there is an empty IO bu er available, then it will load that block into the IO bu er (when reading a FITS le) or will initialize a new block (when writing to a FITS le). If all the IO bu ers are already full, it must decide which one to reuse (generally the one that has been accessed least recently), and ush the contents back to disk if it has been modi ed before loading the new block. The one ma jor 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 bu ers and simply reads or writes the desired bytes directly in the disk le with a single call to a low-level le 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 e cientway 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 e ciently accessing FITS les 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 bu ers, try to access all the needed information in that block before it gets ushed out of the IO bu er. It is importantto avoid the situation where the same FITS block is being read then ushed from a IO bu er multiple times. The following section gives more speci c 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 e cient 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 bu ers, which is somewhat less e cient because of the extra copy operation and additional bookkeeping steps that are required. In principle it is more e cient 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 e ciency factor in the software design is to read or write the data in the FITS le in a single pass through the le. An example of poor program design would be to read a large, 3-column table by sequentially reading the entire rst column, then going back to read the 2nd column, and nally the 3rd column this obviously requires 3 passes through the le 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 ine ciencies can become signi cant. The more e cient procedure in this case is to read or write only as manyrows of the table as will t into the available internal IO bu ers, then access all the necessary columns of data within that range of rows. Then after the program is completely nished with the data in those rows it can move on to the next range of rows that will t in the bu ers, continuing in this wayuntil the entire le 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 le 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 bu ers that have been allocated in CFITSIO, and also on the number of other FITS les that are open at the same time (since one IO bu er is always reserved


56

CHAPTER 5. CFITSIO CONVENTIONS AND GUIDELINES

for each open FITS le). Fortunately, a CFITSIO routine is available that will return the optimal number of rows for a given table: ts 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 ts get rowsize is valid only as long as the application program is only reading or writing data in the speci ed table. Any other calls to access data in the table header or in any other FITS le would cause additional blocks of data to be loaded into the IO bu ers 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 ts 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 e ciency when dealing with tabular data. The I/O to ASCII tables is slower because of the overhead in formatting or parsing the ASCII data elds 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 le. 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 nding 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 t at one time in the available internal IO bu ers, then the header keyword access will be very fast and it makes little di erence which order they are accessed. 5. Avoid the use of scaling (by using the BSCALE and BZERO or TSCAL and TZEROkeywords) in FITS les since the scaling operations add to the processing time needed to read or write the data. In some cases it may be more e cient to temporarily turn o the scaling (using ts set bscale or ts set tscale) and then read or write the raw unscaled values in the FITS le. 6. Avoid using the `implicit datatype conversion' capability in CFITSIO. For instance, when reading a FITS image with BITPIX = -32 (32-bit oating point pixels), read the data into a single precision oating point data array in the program. Forcing CFITSIO to convert the data to a di erent 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 oating pointvalues in the rst column are all written in a contiguous block of the le which can be read or written quickly, whereas in the second case each oating pointvalue in the rst 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 rst 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 ts read tblbytes and ts 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 e ciency) 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 le in exactly the same byte order. For these same reasons, these routines can corrupt the FITS data le 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 le with ts 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 di cult 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 le?). 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 amountofRAM available on the system can all have a signi cant impact on overall I/O e ciency. 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 ts 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 le, passing them to the work function, and then writing any output data back to the FITS le after the work function exits. Because it is often more e cient 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 e ectively replace all the other CFITSIO routines for reading or writing data in FITS images or tables. Using the iterator has several importantadvantages over the traditional method of reading and writing FITS data les: It cleanly separates the data I/O from the routine that operates on the data. This leads to a more modular and `ob ject oriented' programming style. It simpli es 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. It ensures that the data are processed as e ciently as possible. This is especially important when processing tabular data since the iterator function will calculate the most e cient number of rows in the table to be passed at one time to the user's work function on each iteration. Makes it possible for larger pro jects to develop a library of work functions that all have a uniform calling sequence and are all independent of the details of the FITS le format. There are basically 2 steps in using the CFITSIO iterator function. The rst step is to design the work function itself whichmust 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 le or how the output data get written back to the le. The second step is to design the driver routine that opens all the necessary FITS les 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 )

totaln { the total number of table rows or image pixels that will be passed to the work function during 1 or more iterations. o set { the o set applied to the rst 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 o set = 0, then all the table rows or image pixels will be passed to the work function. rstn { the number of the rst table row or image pixel (starting with 1) that is being passed in this particular call to the work function. 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. 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. *data { array of structures, one for each column or image. Each structure contains a pointer to the arrayof dataaswell as other descriptive parameters about that array. *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 modi cation. It may point to a single number, to an arrayofvalues, to a structure containing an arbitrary set of parameters of di erenttypes, or it maybeanull 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, o set, narrays, data, and userPointer parameters are guaranteed to have the same value on each iteration. Only rstn, nvalues, and the arrays of data pointed to by the data structures maychange 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 le. If the work function needs to knowthe number and size of the image dimensions then these parameters can be passed via the userPointer structure. The iteratorCol structure is currently de ned as follows:
typedef struct /* structure for the iterator function column information */ { /* structure elements required as input to fits_iterate_data: */ fitsfile int char int int *fptr colnum colname 70] datatype iotype /* /* /* /* /* pointer to the HDU containing the column or image */ column number in the table ignored for images */ name (TTYPEn) of the column null for images */ output datatype (converted if necessary) */ type: InputCol, InputOutputCol, or OutputCol */

/* output structure elements that may be useful for the work function: */ void long long long char char *array repeat tlmin tlmax unit 70] tdisp 70] /* /* /* /* /* /* /* pointer to the array (and the null value) binary table vector repeat value set equal to 1 for images legal minimum data value, if any legal maximum data value, if any physical unit string (BUNIT or TUNITn) suggested display format null if none */ */ */ */ */ */ */

} iteratorCol

Instead of directly reading or writing the elements in this structure, it is recommended that programmers use the access functions that are provided for this purpose. The rst ve elements in this structure must be initially de ned 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 lls 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 le. 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 les and position them to the correct HDU. It must also initialize the following parameters in the iteratorCol structure (de ned above) for each column or image before calling the CFITSIO iterator function. Several `constructor' routines are provided in CFITSIO for this purpose. *fptr { The ts le pointer to the table or image. 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. colname { the name (TTYPEn keyword) of the column. This is only required if colnum = 0 and is ignored for images. 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 le, 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 anyconversion. iotype { de nes whether the data array is to be input to the work function (i.e, read from the FITS le), or output from the work function (i.e., written to the FITS le) 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
narrays { the number of columns or images that are to be passed to the work function.

63

*data { pointer to array of structures containing information about each column or image. o set { 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. nPerLoop - speci es 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 e ciency. 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. *workFn - the name (actually the address) of the work function that is to be called by ts iterate data. *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. *status - The CFITSIO error status. Should = 0 on input a non-zero output value indicates an error. When ts iterate data is called it rst 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 les. 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, o set, rstn, 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 rst call to the work function rstn will be equal to o set + 1 the work function may need to perform various initialization tasks before starting to process the data. Similarly, rstn + nvalues - 1 will be equal to totaln on the last iteration, at whichpointthe 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 le 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 le 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 rst element in each array that is passed to the work function gives the value that is used to represent null or unde ned values in the array. The real data then begins with the second elementof the array (i.e., array1], not array0]). If the rst array element is equal to zero, then this indicates that all the array elements have de ned values and there are no unde ned values. If array0] is not equal to zero, then this indicates that some of the data values are unde ned and this value (array0]) is used to represent them. In the case of output arrays (i.e., those arrays that will be written back to the FITS le by the iterator function after the work function exits) the work function must set the rst array elementto the desired null value if necessary, otherwise the rst element should be set to zero to indicate that there are no null values in the output array. CFITSIO de nes 2 values, FLOATNULLVALUE and DOUBLENULLVALUE, that can be used as default null values for oat and double datatypes, respectively. In the case of character string datatypes, a null string is always used to represent unde ned 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 rst 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 le and instead may come from any combination of sources as long as they have the same length. The length of the rst 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 functions normally needed to read and write most FITS les. 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 rst 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. Arightarrowsymbol ( ) is used in the function descriptions to separate the input parameters from the output parameters in the de nition of each routine. This symbol is not actually part of the C calling sequence. 3. The function parameters are de ned in more detail in the alphabetical listing in the appendix. 4. The rst argument in almost all the functions is a pointer to a structure of type ` ts le'. Memory for this structure is allocated by CFITSIO when the FITS le is rst opened or created and is freed when the FITS le 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 modi cations 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
void fits_report_error / ffrprt (FILE *stream, > status)

on the CFITSIO stack to the speci ed le stream (normally to stdout or stderr). If the input status value = 0 then this routine does nothing.

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
void fits_clear_errmsg / ffcmsg (void)

may have been generated by a non-fatal CFITSIO error. This routine is called without any arguments.

7.2 FITS File Access Routines
These routines will open or close a new or existing FITS le or return information about the opened FITS le. These routines support the extended le name syntax that is described in a previous chapter. The same FITS le may be opened more than once simultaneously and the resulting pointers to the les may be treated as though they were completely independent FITS les. Thus, one could open a FITS le twice, movetodi erent extensions within the le, and then read or write data to the 2 extensions in any order.

1 Open an existing FITS le with a speci ed access mode. The iomode parameter may have a
value of READONLY or READWRITE.


7.2. FITS FILE ACCESS ROUTINES
int fits_open_file / ffopen (fitsfile **fptr, char *filename, int iomode, > int *status)

67

2 Reopen a FITS le that was previously opened with ts open le or ts create le. The new
ts le pointer write to 2 (or automatically internally call

may then be treated as a separate le, and one may simultaneously read or more) di erent extensions in the same le. The ts open le routine (above) detects cases where a previously opened le is being opened again, and then ts reopen le, 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 le. An error will be returned if the speci ed le already exists unless
the lename the existing used on the backslash to is pre xed with an exclamation point (!). In that case CFITSIO will overwrite le. Note that the exclamation point, ' !', is a special UNIX character, so if it is command line rather than entered at a task prompt, it must be preceded by a force the UNIX shell to ignore it.

int fits_create_file / ffinit (fitsfile **fptr, char *filename, > int *status)

4 Create a new FITS le, using a template le to de ne its initial size and structure. The template

may be another FITS HDU or an ASCII template le. If the input template le name pointer is null, then this routine behaves the same as ts create le. The currently supported format of the ASCII template le is described under the ts parse template routine (in the general Utilities section), but this maychange 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 le.
int fits_close_file / ffclos (fitsfile *fptr, > int *status)

6 Close and DELETE a FITS disk le previously opened with open or nit. This routine may
int fits_delete_file / ffdelt (fitsfile *fptr, > int *status)

be useful in cases where a FITS le is created but then an error occurs which prevents the le from being completed.

7 Return the name of the opened FITS le.


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 le (READONLY or READWRITE).
int fits_file_mode / ffflmd (fitsfile *fptr, > int *iomode, int *status)

9 Return the le type of the opened FITS le (e.g. ' le://', 'ftp://', etc.).
int fits_url_type / ffurlt (fitsfile *fptr, > char *urltype, int *status)

10 Parse the input lename or URL into its component parts: the le type ( le://, ftp://, http://,

etc), the base input le name, the name of the output le that the input le is to be copied to prior to opening, the HDU or extension speci cation, the ltering speci er, the binning speci er, and the column speci er. Null strings will be returned for any components that are not present in the input le 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 lename and return the HDU number that would be moved to if the le were

opened with ts open le. The returned HDU number begins with 1 for the primary array, so for example, if the input lename = `my le. ts2]' then hdunum = 3 will be returned. If an extension name is included in the le name speci cation (e.g. `my le. tsEVENTS]' then this routine will have to open the FITS le and look for the position of the named extension, then close le. This is not possible if the le is being read from the stdin stream, and an error will be returned in this case. If the lename does not specify an explicit extension (e.g. 'my le. ts') 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 e cient to rst open the FITS le with ts open le, then use ts get hdu num to determine which HDU in the le has been opened, rather than calling ts parse input url then calling ts open le.

int fits_parse_extnum / ffextn (char *filename, > int *hdunum, int *status)

12 Parse the input le name and return the root le name. The root name includes the le

type if speci ed, (e.g. 'ftp://' or 'http://') and the full path name, to the extent that it is speci ed in the input lename. It does not enclude the HDU name or number, or any ltering speci cations.

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 speci ed absolute HDU number in the FITS le. When a FITS le is rst opened or

created it is automatically positioned to the rst HDU (the primary array) in the le which has hdunum = 1. Anull 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 relativenumber of HDUs forward or backwards in the FITS le from the current position.
Anull 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 ( rst) HDU which has the speci ed extension type and EXTNAME (or HDUNAME)

and EXTVERS keyword values. The hdutype parameter mayhavea 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 rst HDU with a matching EXTNAME (or HDUNAME) keyword will be found. If no matching HDU is found in the le 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 le (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 le. 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 le. 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 le is currently empty then a
primary array is created, otherwise a new IMAGE extension is appended to the le.
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 le is currently empty then a

dummy primary array will be created before appending the table extension to it. The tbltype parameter de nes 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 speci ed 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 de ned. 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 signi cant. It is recommended that all the column names in a given table be unique within the rst 8 characters, and strongly recommended that the names be unique within the rst 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 le associated with infptr and append it to the end of the FITS
int fits_copy_hdu / ffcopy (fitsfile *infptr, fitsfile *outfptr, int morekeys, > int *status)

le associated with outfptr. Space may be reserved for MOREKEYS additional keywords in the output header.

10 Delete the CHDU in the FITS le. Any following HDUs will be shifted forward in the le, to ll

in the gap created by the deleted HDU. This routine will only delete extensions the primary array (the rst HDU in the le) cannot be deleted. The physical size of the FITS le will not necessarily be reduced. If there are more extensions in the le following the one that is deleted, then the the CHDU will be rede ned to point to the following extension. If there are no following extensions then the CHDU will be rede ned 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 matchany single character at that position in the keyword name and a '*' will match any length (including zero) string of characters. The '#' character will matchany 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 backto the original header position as is done when no wildcards are included in the keyword name. The ts 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 speci ed 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. Anull pointer maybeentered 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 speci es 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 eld 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 eld if the keyword already exists in the header, otherwise it will append 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 speci es 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, TCOMPLEX, and TDBLCOMPLEX. A null pointer may be entered for the comment parameter whichwill leave the comment eld blank (or unmodi ed).

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 unde ned value (i.e., the value eld in the keyword is left blank).

This routine will modify the value and comment eld if the keyword already exists in the header, otherwise it will append a new null-valued keyword at the end of the header. Anull pointer maybe entered for the comment parameter whichwill leave the comment eld blank (or unmodi ed).

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 HISTORYkeyword to the CHU. The comment string will be split over multiple
HISTORYkeywords 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
int fits_write_date / ffpdat (fitsfile *fptr, > int *status)

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.

8 Write a user speci ed 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 elds. If the keyword doesn't already exist then a new keyword card is appended to the header.


7.4. HEADER KEYWORD READ/WRITE ROUTINES
int fits_update_card / ffucrd (fitsfile *fptr, char *keyname, char *card, > int *status)

73

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 eld.
12.3 / km/s] orbital speed VELOCITY=

int fits_write_key_unit / ffpunt (fitsfile *fptr, char *keyname, char *unit, > int *status)

11 Rename an existing keyword preserving the currentvalue and comment elds.
int fits_modify_name / ffmnam (fitsfile *fptr, char *oldname, char *newname, > int *status)

12 Modify (overwrite) the comment eld 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 rst 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 subsequentkeyword 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 speci ed keyword name.
int fits_read_card / ffgcrd (fitsfile *fptr, char *keyname, > char *card, int *status)

15 Read a speci ed keyword value and comment. The datatype parameter speci es 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 conversion will be performed for numeric values if the keyword value does not have the same datatype. If the value of the keyword is unde ned (i.e., the value eld is blank) then an error status = VALUE UNDEFINED will be returned. If a NULL commentpointer 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 eld. Anull string is returned if no units are de ned for the keyword.
12.3 / km/s] orbital speed

VELOCITY=

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 bymov-

ing all the following header records up one row in the header. The rst routine deletes a keyword at a speci ed position in the header (the rst keyword is at position 1), whereas the second routine deletes a speci cally named keyword. Wild card characters may be used when specifying the name of the keyword to be deleted.
> int *status)

int fits_delete_record / ffdrec (fitsfile *fptr, int keynum,

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

de ne the columns or arrays. These set the ts le 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
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)

75

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 rst HDU in a FITS le) or an IMAGE extension. These routines simply treat the array as a long 1-dimensional arrayof pixels ignoring the intrinsic dimensionality of the arrayasde ned by the NAXISn keywords. When dealing with a 2D image, for example, the application program must calculate the pixel o set 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 les, 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 array50]100] and not as array100]50]. The `datatype' parameter speci es 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 de ned by the BITPIX keyword) di ers from that speci ed by 'datatype'. The data values are also automatically scaled by the BSCALE and BZEROkeyword 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 de ne 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 BINARYTABLE ROUTINES
int fits_write_img / ffppr (fitsfile *fptr, int datatype, long firstelem, long nelements, DTYPE *array, int *status)

77

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 de ned by the BLANK keyword (an error is returned if the BLANK keyword doesn't exist). For oating point FITS arrays the special IEEE NaN (Not-a-Number) value will be written into the FITS le. If a null pointerisentered for nulval, then the null value is ignored and this routine behaves the same as ts 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 de ned by the BLANK keyword (an error is returned if the BLANK keyword doesn't exist). For oating point FITS arrays the special IEEE NaN (Not-a-Number) value will be written into the FITS le.

int fits_write_null_img / ffpprn (fitsfile *fptr, long firstelem, long nelements, > int *status)

8 Read elements from the FITS data array. Unde ned FITS arrayelements will be returned with

avalue = *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 unde ned 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 unde ned 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 rst 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
int fits_get_num_rows / ffgnrw (fitsfile *fptr, > long *nrows, int *status) int fits_get_num_cols / ffgncl (fitsfile *fptr, > int *ncols, int *status)

the NAXIS2 keyword and the number of columns is given by the TFIELDS keyword in the header of the table.

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 maycontain the integer number of the desired column (with the rst column = 1). The `*' wild card character matches any sequence of characters (including zero characters) and the `?' character matches any single character. The # wildcard will matchany consecutive string of decimal digits (0-9). If more than one column name in the table matches the template string, then the rst match is returned and the status value will be set to COL NOT UNIQUE as a warning that a unique matchwas not found. To nd 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 significant. It is recommended that all the column names in a given table be unique within the rst 8 characters, and strongly recommended that the names be unique within the rst 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, TCOMPLEX and TDBLCOMPLEX. Note that if the column is a 32-bit integer, then this routine


7.7. ASCII AND BINARYTABLE 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 negative 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 speci ed 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 xed 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. Anull 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 ts 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 naxes0] 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 naxes0] equal to the repeat count in the TFORM keyword. This routine is called by ts 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 rowFROW 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 re ect 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 ll in the space. This routine modi es the NAXIS2 keyword to re ect the new number of rows in the table. The physical size of the FITS le may not be reduced by this operation, in which case the empty FITS blocks if anyat the end of the le 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 numbers must be sorted in ascending order. The physical size of the FITS le may not empty FITS blocks if anyat the end of the

rst row in the table is 1 not 0). The list of row nrows is the number of rownumbers in the list. be reduced by this operation, in which case the le 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 speci es the

column number that the ( rst) new column should occupy in the table. NCOLS species 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 re ect the new position of the column(s) in the table: TBCOLn, TFORMn, TTYPEn, TUNITn, TNULLn, TSCALn, TZEROn, 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 BINARYTABLE ROUTINES
'1E' to '20E'). The vector length may be increased or decreased from the currentvalue.

81

5 Modify the vector length of a binary table column (e.g., change a column from TFORMn =
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 re ect the new position of the column(s) in the table. The physical size of the FITS le may not be reduced by this operation, and the emptyFITSblocks if any at the end of the le 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 rst 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 (de ned bythe TFORMn keyword) di ers 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 de nes the starting pixel within the cell (a cell is de ned 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 speci es 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 le is de ned by the TNULLn keyword and an error is returned if the TNULLn keyword doesn't exist. For oating 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 thesameas ts 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 unde ned. For all ASCII table columns and for integer

columns in binary tables, the null value to be used in the FITS le is de ned by the TNULLn keyword and an error is returned if the TNULLn keyword doesn't exist. For oating 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 speci es the

datatype of the `nulval' and `array' pointers Unde ned array elements will be returned with avalue = *nullval, (note that this parameter gives the address of the null value, not the null value itself ) unless nulval=0 or *nulval = 0, in whichcase nochecking for unde ned 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 ts get col display width routine. The following TDISPn display formats are currently supported:


7.8. CELESTIAL COORDINATE SYSTEM ROUTINES
Iw.m Ow.m Zw.m Fw.d Ew.d Dw.d Gw.d Integer Octal integer Hexadecimal integer Fixed floating point Exponential floating point Exponential floating point General uses Fw.d if significance not lost, else Ew.d

83

where w is the width in characters of the displayed values, m is the minimum number of digits displayed,and disthe number of digits to the right of the decimal. The .m eld 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 speci es the

datatype of the and `array' pointer Any unde ned 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 de ne the parameters to be used when calculating the coordinate transformation. Both sets of routines require that a 2 step procedure be followed: rst 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 rst set of routines described belowhave 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 pro jections 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 de ned WCS map pro jections and they support a number of non-standard keyword conventions that have been adopted over the years by various di erent 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 pro jections: -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 rst coordinate axis is the declination-like coordinate, then this routine will swap them so that the longitudinal-like coordinate is returned as the rst axis. If the le 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 de ned 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 su ciently 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
(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)

85

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 le (e.g., wcssubs-2.5.tar.gz) or as a zipped le (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 de ned pro jection geometries, and they also support most standard as well as many non-standard WCS keyword conventions that have been used by di erent 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 rst 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 convenientinterface 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 mustbefreedby 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 eachevent 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 byany 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 de ned 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 de ned in the wcs structure. The returned o scale parameter equals 0 if the coordinate is within bounds of the image. This is a WCS library routine.


7.9. HIERARCHICAL GROUPING CONVENTION SUPPORTROUTINES
void wcs2pix (struct WorldCoor *wcs, double xpos, double ypos, > double *xpix, double *ypix, int *offscale)

87

7 Free the WCS structure that was created bywcsinit. This isaWCS 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 de ned in "A Hierarchical Grouping Convention for FITS" by Jennings, Pence, Folk and Schlesinger ( http: //adfwww.gsfc.nasa.gov/other/convert/group.html ). A group is a collection of HDUs whose association is de ned 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 eachmember HDU. The grouping table columns provide identi cation information that allows applications to reference or "point to" the member HDUs. Member 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 le as its grouping table, and that a given HDU may be referenced byup to 999 grouping tables simultaneously. Grouping tables are implemented as FITS binary tables with up to six pre-de ned column TTYPEn values: 'MEMBER XTENSION', 'MEMBER NAME', 'MEMBER VERSION', 'MEMBER POSITION', 'MEMBER URI TYPE' and 'MEMBER LOCATION'. The rst three columns allow member HDUs to be identi ed by reference to their XTENSION, EXTNAME and EXTVER keyword values. The fourth column allows member HDUs to be identi ed by HDU position within their FITS le. The last two columns identify the FITS le in which the member HDU resides, if di erent from the grouping table FITS le. Additional user de ned "auxiliary" columns may also be included with any grouping table. When a grouping table is copied or modi ed 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 de ned but the corresponding member HDU information is unavailable then a null value of the appropriate data type is inserted in the column eld. Integer columns (MEMBER POSITION, MEMBER VERSION) are de ned with a TNULLn value of zero (0). Character eld columns (MEMBER XTENSION, MEMBER NAME, MEMBER URI TYPE, MEMBER LOCATION) utilize an ASCII null character to denote a null eld value. The grouping support functions belong to two basic categories: those that work with grouping table HDUs ( gt**) and those that work with member HDUs ( gm**). Two functions, ts copy group() and ts 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 de ned groups could cause unpredictable results. The problem of a grouping table directly or indirectly referencing itself (thus creating an in nite 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 le 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 speci ed. The grouptype parameter speci es 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 le URI columns), and GT ID POS URI (ID by position and FITS le 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 le 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 speci ed. The grouptype parameter species the desired structure of the grouping table and maytake 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 byreference and FITS le URI columns), and GT ID POS URI (ID by position and FITS le 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 ts create group() for valid parameter values) speci es 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 lled with the null values appropriate to the column type.

int fits_change_group / ffgtch (fitsfile *gfptr, int grouptype, > int *status)

4 Remove the group de ned by the grouping table pointed to by gfptr, and optionally all the

group member HDUs. The rmopt parameter speci es the action to be taken for all members


7.9. HIERARCHICAL GROUPING CONVENTION SUPPORTROUTINES

89

of the group de ned 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 re ect the deletion accordingly.
int fits_remove_group / ffgtrm (fitsfile *gfptr, int rmopt, > int *status)

5 Copy (append) the group de ned by the grouping table pointed to by infptr, and optionally all
group member HDUs, to the FITS le pointed to by outfptr. The cpopt parameter speci es 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 de ned by infptr). If the cpopt == OPT GCP GPT then the members of infptr have their GRPIDn and GRPLCn keywords updated to re ect 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 de ned by infptr will be copied to a single FITS le pointed to by outfptr regardless of their le distribution in the original group.

int fits_copy_group / ffgtcp (fitsfile *infptr, fitsfile *outfptr, int cpopt, > int *status)

6 Merge the two groups de ned by the grouping table HDUs infptr and outfptr by combining
their members into a single grouping table. to outfptr. If mgopt == OPT MRG COPY merge. If the mgopt == OPT MRG MOV cases, the GRPIDn and GRPLCn keywords

All member HDUs (rows) are copied from infptr then infptr continues to exist unaltered after the then infptr is deleted after the merge. In both of the member HDUs are updated accordingly.

int fits_merge_groups / ffgtmg (fitsfile *infptr, fitsfile *outfptr, int mgopt, > int *status)

7 "Compact" the group de ned by grouping table pointed to bygfptr. The compaction is achieved

by merging (via ts merge groups()) all direct member HDUs of gfptr that are themselves grouping tables. The cmopt parameter de nes 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
are accessible and that all links to other grouping tables are valid. The rstfailed parameter returns the member ID (rownumber) of the rst member HDU to fail veri cation (if positive value) or the rst group link to fail (if negative value). If gfptr is successfully veri ed then rstfailed contains a return value of 0.

8 Verify the integrity of the grouping table pointed to by gfptr to make sure that all group members

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 de ned 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 le other than the member HDUs le then an attempt is rst made to open the le 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 keywords in a member HDU header to be non-continuous, e.g., GRPID1, GRPID2, GRPID5, GRPID6. In such cases, the grpid index value speci ed in the function call shall identify the (grpid)th GRPID value. In the above example, if grpid == 3, then the group speci ed 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 (whichmust be positioned to the member HDU) or, if mfptr == NULL, identi ed 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 le. 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 (numberofrows) 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 de ned by
the number of GRPIDn/GRPLCn keyword records that appear in its header. Note that each


7.9. HIERARCHICAL GROUPING CONVENTION SUPPORTROUTINES

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 identi ed by

its rownumber within the grouping table as given by the parameter 'member' ( rst member == 1) . A ts le pointer to the opened member HDU is returned as mfptr. Note that if the member HDU resides in a FITS le di erent from the grouping table HDU then the member le is rst 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 bygfptr. The member HDU

is identi ed byits rownumber within the grouping table as given by the parameter 'member' ( rst member == 1). The copy of the group member HDU will be appended to the FITS le pointed to by mfptr, and upon return mfptr shall point to the copied member HDU. The cpopt parameter maytake 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 identi ed by its row number within infptr as speci ed by the parameter 'member' ( rst 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 identi ed by its row number in the grouping table as speci ed by the parameter 'member' ( rst member == 1). The rmopt parameter may take on the following values: OPT RM ENTRY whichremoves the member HDU entry from the grouping table and updates 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 de ned arithmetic expression. The rst 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 lter 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 ags indicating
whichrows 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 rst row which satis es 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 les are not the same,
int fits_select_rows / ffsrow (fitsfile *infptr, fitsfile *outfptr,

copy the TRUE rows to the output le. If the les are the same, delete the FALSE rows (preservethe TRUE rows).
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 ts 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 speci ed 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 speci ed row ranges. nranges speci es the number of row ranges, and rstrow and lastrow give the starting and ending rownumber 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 le has been modi ed 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
current header. If the keywords already exist, their values will be updated only if necessary (i.e., if the le has been modi ed since the original keyword values were computed).

1 Compute and write the DATASUM and CHECKSUM keyword values for the CHDU into the
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 veri ed 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 veri ed 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 vcks, 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
unsigned long fits_decode_chksum / ffdsum (char *ascii, int complm, > unsigned long *sum)

32-bit sum value will be complemented after decoding. The checksum value is also returned as the value of the function.


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
int fits_get_system_date/ffgsdt ( > int *day, int *month, int *year, int *status )

date and time, but this routine is provided for compatibility with the Fortran FITSIO library. The returned year has 4 digits (1999, 2000, etc.)

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, inclusive, 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 ts 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 speci es 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 anyunwanted 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 anyunwanted 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 matchanysingle 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 rst null character in the header, or zero if there are no nulls. For example a returned value of 110 would indicate that the rst 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.
int fits_get_keyname / ffgknm (char *card, > char *keyname, int *keylength, int *status)

The keyword name normally occupies the rst 8 characters of the record, except under the HIERARCH convention where the name can be up to 70 characters in length.

7 Parse a header keyword record, returning the value (as a literal character string) and comment
int fits_parse_value / ffpsvc (char *card, > char *value, char *comment, int *status)

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.

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, oating point, or complex, respectively.
int fits_get_keytype / ffdtyp (char *value, > char *dtype, int *status)


98

CHAPTER 7. BASIC CFITSIO INTERFACE ROUTINES
catagories (the class values are de ned in tsio.h). Note that this is one of the few CFITSIO routines that does not return a status value.
Keywords 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. The experimental keywords used in the compressed image format ZIMAGE, ZCMPTYPE, ZNAMEn, ZVALn, ZTILEn, ZBITPIX, ZNAXISn, ZSCALE, ZZERO, ZBLANK BSCALE, BZERO, TSCALn, TZEROn BLANK, TNULLn TDIMn TLMINn, TLMAXn, TDMINn, TDMAXn, DATAMIN, DATAMAX BUNIT, TUNITn TDISPn EXTNAME, EXTVER, EXTLEVEL, HDUNAME, HDUVER, HDULEVEL CHECKSUM, DATASUM 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) EQUINOXs, EPOCH, MJD-OBSs, RADECSYS, RADESYSs COMMENT, HISTORY, (blank keyword) CONTINUE all other keywords

11 Return the class of input header record. The record is classi ed into one of the following

Class Value TYP_STRUC_KEY 10

TYP_CMPRS_KEY

20

TYP_SCAL_KEY 30 TYP_NULL_KEY 40 TYP_DIM_KEY 50 TYP_RANG_KEY 60 TYP_UNIT_KEY 70 TYP_DISP_KEY 80 TYP_HDUID_KEY 90 TYP_CKSUM_KEY 100 TYP_WCS_KEY 110

TYP_REFSYS_KEY TYP_COMM_KEY TYP_CONT_KEY TYP_USER_KEY

120 130 140 150

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 eld, and, in the case of character string elds, 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 de nes 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 oating 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 de ned to be short integers (code = TSHORT). Wider integer columns are de ned to be regular integers (code = TLONG). Similarly, Fixed decimal point columns (with TFORM = 'Fw.d') are de ned 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 de nes howmany 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 appending to (or an ASCII ted string append or deleting from) a FITS header le. This routine is useful for parsing lines from template le and reformatting them into legal FITS header records. The formatmay then be passed to the ts write record, mcrd, or ts delete key routines to 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 anylowercase characters to uppercase in the output string. If the rst 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
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. at least one blank space and a '/' character.

- The VALUE token must be separated from the KEYNAME token by one or more spaces and/or

- The COMMENT token is optional, but if presentmust be separated from the VALUE token by - One exception to the above rules is that if the rst non-blank character in the rst 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. 2 tokens (without an equals sign between them) then the second token is interpreted as the new name for the keyword speci ed by rst token. In this case the old keyword name ( rst 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 mnam routine which will change the keyword name.

- The second exception is that if the template string starts with a minus sign and is followed by

The keytype output parameter indicates how the returned CARD string should be interpreted:
keytype -------2 interpretation ------------------------------------------------Rename the keyword with name = the first 8 characters of CARD to the new name given in characters 41 - 48 of CARD. delete the keyword with this name from the FITS header. 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. This is a HISTORY or COMMENT keyword END record append it to the header

-1 0

1 2

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 34.6 / This is a floating point keyword RVAL


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 ll 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 ll bytes (if any) are all zero (for IMAGE or BINARYTable HDU) or all
blanks (for ASCII table HDU). These le 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 di erent calling sequence.

8.1 Specialized FITS File Access Routines
1 Open a FITS le residing in core computer memory. This routine analogous to ts open le.
In general, the application must preallocate an initial block of memory to hold the FITS le: 'bu ptr' points to the starting address and 'bu size' 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 de ned FITS le (as given by the NAXISn keywords)or1FITS block(= 2880 bytes), whichever 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
called, but can be useful when writing to the FITS les in memory, and will ensure that if the program subsequently aborts then the FITS le will have been closed properly.

2 Flush any internal bu ers of data to the output FITS le. This routine rarely needs to be
int fits_flush_file / ffflus (fitsfile *fptr, > int *status)

8.2 Specialized HDU Access Routines
1 Get the byte o sets in the FITS le to the start of the header and the start and end of the
data in the CHDU. The di erence between headstart and dataend is the size of the CHDU. If the CHDU is the last HDU in the le, then dataend is also equal to the size of the entire FITS le. 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 le. This is now the CHDU but it
is completely empty and has no header keywords. It is recommended that ts create img or ts 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 le. The new extension will become the CHDU. Refer to Chapter 9 for a list of pre-de ned 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 le. If the FITS le is currently empty then this routine will create adummy 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 de ned. When inserting an ASCII table with ts 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 ts insert btbl, if there are following extensions in the le and if the table contains variable length array columns then pcountmust specify the expected nal 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 speci ed by the input arguments, is larger than the current existing image in the FITS le then zero ll data will be inserted at the end of the current image and any following extensions will be moved further back in the le. 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 le 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 le. 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 ts copy hdu, but it may also be useful in certain application programs that wanttocopy the data from one FITS le to another but also wanttomodify the header keywords. The required FITS header keywords which de ne 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 de ne the structure
of the HDU (such as the NAXIS and BITPIX keywords) so that it reinitializes the bu ers that describe the HDU structure. This routine is useful for reinitializing the s of an HDU if any of the required keywords (e.g., NAXISn) have been modi ed. In it should rarely be necessary to call this routine because CFITSIO internally calls it situations.
(DEPRECATED)

internal tructure practice in most

int fits_set_hdustruc / ffrdef (fitsfile *fptr, > int *status)

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 e cient 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 ts write imghdr
routine is equivalent to calling ts 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 recommended that ts create image or ts create tbl be used instead of these routines to write the required header keywords.


8.3. SPECIALIZED HEADER KEYWORD ROUTINES
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)

107

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. Anull pointer maygiven 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 speci es the size of the variable length array heap, should initially = 0 CFITSIO will automatically update the PCOUNT keyword value if anyvariable 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 speci ed when the table is created (e.g., the input TFORMn value is just '1Pt') then CFITSIO will scan the column when the table is rst closed and will append the maximum length to the TFORM keyword value. Note that if the table is subsequently modi ed 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 anyof
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 ts 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 unde ned, 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 eld 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 whichmay 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 ts write key longwarn routine to add some COMMENT keywords to warn users of the FITS le that this convention is being used. The ts 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 ts 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 commentto 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 ( rst) COMMENTS string parameter. This same string will then be used for the comment eldinall the keywords. One may also enter a null pointer for the comment parameter to leave the comment eld 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 input HDU (bygiving keyroot = "TLMIN" and innum = 3) with the keyword name TLMIN4 (by setting outnum = 4). exist, then this routine simply returns without indicating an

the TLMIN3 keyword from the and write it to the output HDU If the input keyword does not 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 oating 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 gkyt 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 de ned in an ASCII template le. The format of the
template le is described under the ts 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 e cient 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 speci ed 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. Anull pointer maybeentered for the comment parameter which will cause the comment eld 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
(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)

111

3 Insert a new keyword with an unde ned, 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 de ned value (i.e., if the value eld 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 matchany

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 searchfrom the top of the header back to the original position. The current header position may be reset with the grec 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
this routine simply returns the string of characters in the value eld of the keyword along with the comment eld. If a NULL comment pointer is given on input, then the comment string will not be returned.

3 Read the literal keyword value as a character string. Regardless of the datatype of the keyword,

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 de ned (i.e., the value eld 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 anyof the keywords is not de ned (i.e., the value eld is blank) then an error status = VALUE UNDEFINED will be returned and the input value for the unde ned 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 oating point keyword, returning the integer and fractional parts of the
int fits_read_key_triple / ffgkyt (fitsfile *fptr, char *keyname, > long *intval, double *frac, char *comment, int *status)

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

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 modi ed.

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 elds.
int fits_modify_card / ffmcrd (fitsfile *fptr, char *keyname, char *card, > int *status)

5 Modify the value and comment elds 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 eld and leave the comment eld unchanged by setting the input COMMENT parameter equal to the ampersand character (&) or byentering 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 unde ned, or null. The value string of the keyword
int fits_modify_key_null / ffmkyu (fitsfile *fptr, char *keyname, char *comment, > int *status)

is set to blank. Optionally, one mayleave the comment eld unchanged by setting the input COMMENT parameter equal to the ampersand character (&) or byentering a null pointer.

8.3.7 Specialized Update Keyword Routines
1 These update routines modify the value, and optionally the comment eld, 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 functionalityas the `str' version except that it also supports the local long string keyword convention for strings longer than 68 characters. Anull pointer maybeentered for the comment parameter which will leave the comment eld 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 De ne Data Scaling and Unde ned Pixel Parameters
These routines de ne or modify the internal parameters used by CFITSIO to either scale the data or to represent unde ned 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 le. Similarly, CFITSIO generally uses the value of the BLANK or TNULLn keyword to signify an unde ned pixel, but these routines maybe used tooverride 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 BZEROkeyword values and only a ects the automatic scaling performed when the data elements are written/read to/from the FITS le. When reading from a FITS le 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 le.

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 a ects the automatic scaling performed when the data elements are written/read to/from the FITS le. When reading from a FITS le 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 le.

int fits_set_tscale / fftscl (fitsfile *fptr, int colnum, double scale, double zero, > int *status)

3 De ne the integer value to be used to signify unde ned 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 De ne the string to be used to signify unde ned 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 De ne the value to be used to signify unde ned pixels in an integer column in a binary table
int fits_set_btblnul / fftnul (fitsfile *fptr, int colnum, long nulval, > int *status)

(where TFORMn = 'B', 'I', or 'J'). This does not create or change the value of the TNULLn keyword.


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 rst HDU in the FITS le) or an IMAGE extension. Automatic data type conversion is performed for if the data type of the FITS array (as de ned by the BITPIX keyword) di ers 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 speci cally support the FITS random groups format. The more primitive reading and writing routines (i. e., ppr , ppn , ppn, gpv ,or gpf ) 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 o set 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 les, 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 array50]100] and not as array100]50]. For convenience, higher-level routines are also provided to speci cly deal with 2D images ( p2d and g2d ) and 3D data cubes ( p3d and g3d ). 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 arraymay 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 ll the lower left corner of the array with pixels in the range 1 - 400 in the X an Y directions. This has the e ect 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 ( pss , gsv , and gsf ) 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 ( gsv and gsf ) also have an `inc' parameter which de nes the data sampling interval in each dimension of the FITS array. For example, if inc0]=2 and inc1]=3 when reading a 2-dimensional FITS image, then only every other pixel in the rst dimension and every 3rd pixel in the second dimension will be returned to the 'array' parameter. Twotypes of routines are provided to read the data array which di er in the way unde ned pixels are handled. The rst type of routines (e.g., gpv ) simply return an array of data elements in which unde ned pixels are set equal to a value speci ed by the user in the `nulval' parameter. An


8.5. SPECIALIZED FITS PRIMARYARRAYOR IMAGE EXTENSION I/O ROUTINES 117
additional feature of these routines is that if the user sets nulval = 0, then no checks for unde ned pixels will be performed, thus reducing the amount of CPU processing. The second type of routines (e.g., gpf ) returns the data element array and, in addition, a char array which de nes whether the corresponding data pixel is de ned (= 1) or not (= 0). The latter type of routines maybe more convenient to use in some circumstances, however, it requires an additional array of logical values whichcan be unwieldy when working with large data arrays.

1 Write elements into the data array. The datatype is speci ed by the su x 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 thedataarray, substituting the appropriate FITS null value for all elements

which are equal to the value of NULLVAL. For integer FITS arrays, the null value de ned by the BLANK keyword or a previous call to pnul will be substituted for oating 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 unde ned.
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 o cally 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. Unde ned array elements will be returned with a value =
nullval, unless nullval = 0 in whichcase no checks for unde ned 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 null ags from data array. Any unde ned 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 o cally deprecated for future use.
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) int


8.6. SPECIALIZED FITS ASCII AND BINARYTABLE ROUTINES

119

12 Read 2-D image from the data array. Unde ned pixels in the array will be set equal to the value
of 'nulval', unless nulval=0 in which case no testing for unde ned pixels will be performed.
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) int

13 Read 3-D cube from the data array. Unde ned pixels in the array will be set equal to the value
of 'nulval', unless nulval=0 in which case no testing for unde ned pixels will be performed.
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) int

14 Read an arbitrary data subsection from the data array. Unde ned pixels in the array will be set
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)

equal to the value of 'nulval', unless nullval=0 in which case no testing for unde ned pixels will be performed.

15 Read an arbitrary data subsection from the data array. Any Unde ned 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. Anull pointer maybe given for anyof
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 de ned by the TFORMn keyword (e.g., 'I', 'J','E', 'D', etc.). In the case of an ASCII character column, typecode will havea value of the form 'An' where 'n' is an integer expressing the width of the eld in characters. For example, if TFORM = '160A8' then gbcl will return typechar='A8' and repeat=20. All the returned parameters are scalar quantities. Anull 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 e ciency. Refer
int fits_get_rowsize / ffgrsz (fitsfile *fptr, long *nrows, *status)

to the \Optimizing Code" section in Chapter 5 for more discussion on how to use this routine.

4 De ne the zero indexed byte o set 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 phbn) and after the table structure has been de ned (with bdef ) 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 e cientwaytocopy all or part of a table from one location to another. These routines simply read or write the speci ed 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 anymachine dependentdata conversion or byte swapping.


8.6. SPECIALIZED FITS ASCII AND BINARYTABLE ROUTINES

121

1 Read a consecutivearrayofbytes 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 arrayofbytes 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 su x 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
int fits_write_colnul_str / ffpcns (fitsfile *fptr, int colnum, long firstrow, long firstelem, long nelements, char **array, char *nulstr, > int *status)

for any elements that are equal to the nulstr string. This routine must NOT be used to write to variable length array columns.


122

CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES
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 eachbyte whether they are formally valid or not. Thus if the column is de ned as '4X', and one calls pclx with rstbit=1 and nbits=8, then all 8 bits will be written into the rst byte (as opposed to writing the rst 4 bits into the rst row and then the next 4 bits into the next row), even though the last 4 bits of each byte are formally not de ned.

4 Write bit values into a binary byte ('B') or bit ('X') table column (in the CDU). Larray is an

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 pointto 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
Twotypes of routines are provided to get the column data which di er in the way unde ned pixels are handled. The rst set of routines ( gcv) simply return an array of data elements in which unde ned pixels are set equal to a value speci ed by the user in the 'nullval' parameter. If nullval =0, thennochecks for unde ned pixels will be performed, thus increasing the speed of the program. The second set of routines ( gcf ) returns the data elementarray and in addition a logical arrayof ags which de nes whether the corresponding data pixel is unde ned. 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 ts get col display width routine. The following TDISPn display formats are currently supported:
Iw.m Ow.m Zw.m Fw.d Ew.d Dw.d Gw.d Integer Octal integer Hexadecimal integer Fixed floating point Exponential floating point Exponential floating point General uses Fw.d if significance not lost, else Ew.d


8.6. SPECIALIZED FITS ASCII AND BINARYTABLE ROUTINES

123

where w is the width in characters of the displayed values, m is the minimum number of digits displayed, anddis the number of digits to the right of the decimal. The .m eld is optional.

1 Read elements from an ASCII or binary table column (in the CDU). These routines return the

values of the table column arrayelements. Unde ned array elements will be returned with a value = nulval, unless nulval = 0 (or= ''for gcvs)in whichcase no checking for unde ned values will be performed. The ANYF parameter is set to true if any of the returned elements are unde ned.

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 ags from an ASCII or binary table column (in the CHDU). These

routines return the values of the table column array elements. Any unde ned 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 unde ned.

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.
Unde ned pixels in the array will be set equal to the value of 'nulval', case no testing for unde ned pixels will be performed. The rst and be read are speci ed by fpixels(naxis+1) and lpixels(naxis+1), and next higher dimension of the FITS N-dimensional array. The INC sampling interval in each dimension between the data elements that

unless nulval=0 in which last rows in the table to hence are treated as the parameter speci es the 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 Unde ned pixels in the array will have the corresponding 'nularray' element set equal to TRUE. The rst and last rows in the table to be read are speci ed by fpixels(naxis+1) and lpixels(naxis+1), and hence are treated as the next higher dimension of the FITS Ndimensional array. The INC parameter speci es 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 de ned as '4X', and one calls gcx with rstbit=1 and nbits=8, then all 8 bits will be read from the rst byte (as opposed to reading the rst 4 bits from the rst row and then the rst 4 bits from the next row), even though the last 4 bits of eachbyte are formally not de ned.

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 gcxui and gcxuk, respectively. If nrows is greater than 1, then the same set of bits will be read from eachrow, starting with rstrow. The bits are numbered with 1 = the most signi cant bit of the rst 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 o set relativeto the start of the heap. The rst 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 BINARYTABLE ROUTINES
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)

125


126

CHAPTER 8. SPECIALIZED CFITSIO INTERFACE ROUTINES


127


128

APPENDIX A. INDEX OF ROUTINES

Appendix A

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


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

ts ts ts ts ts ts ts ts ts ts ts ts ts ts ts ts ts ts ts

write write write write write write write write write write write write write write write write write write write

img TYP imghdr imgnull imgnull TYP key key longstr key longwarn key null key template key triple key unit key TYP keys TYP null img record subset TYP tblbytes tdim theap

117 106 77 117 71 109 109 108 110 110 73 108 109 77 72 118 121 79 120


130 asfm bnfm calc calc rng clos cmps cmsg copy cpcl cpdt cphd cpky crhd crim crow crtb dcol delt dhdu dkey drec drow drws dsum dt2s dtdm dtyp esum extn rw md nm us frow g2d g3d gabc gacl gbcl gcdw gcf gcf gcks gcnn gcno gcrd 99 98 93 93 67 96 66 70 81 105 105 109 104 70 92 70 81 67 70 74 74 80 80 94 95 79 97 94 68 92 68 67 104 92 119 119 99 119 120 79 83 123 94 78 78 73 gcv gcv gcx gdes gdess gerr ggp ghad ghbn ghdn ghdt ghpr ghps ghsp ghtb gics gidm gidt gipr gisz gkcl gkey gkls gkn gknm gky gkyn gkyt gky gmcp gmng gmop gmrm gmsg gmtf gncl gnrw gnxk gpf gpf gpv gpv grec grsz gsdt 119 gsf 83 123 124 124 124 66 118 104 108 69 69 107 106 71 107 84 76 76 76 76 98 112 112 112 97 73 111 113 112 91 91 91 91 66 91 78 78 111 77 118 77 118 73 120 95 124

APPENDIX A. INDEX OF ROUTINES
gstm 95 gsv 119 123 gtam 90 gtbb 121 gtch 88 gtcl 79 gtcm 89 gtcp 89 gtcr 88 gtcs 84 gtdm 79 99 gthd gtis 88 gtmg 89 gtnm 90 gtop 90 gtrm 89 gtvf 90 gunt 74 hdef 106 bin 105 cls 80 col 80 img 104 kls 110 kyu 111 ky 110 nit 67 rec 110 row 80 tab 105 ter 75 url 68 keyn 97 mahd 69 mcom 73 mcrd 113 mkls 113 mkyu 114 mky 113 mnam 73 mnhd 69 mrec 113 mrhd 69 mvec 81 nchk 97 nkey omem open p2d p3d pcks pcl pcls pcl pcn pcn pcom pdat pdes pgp phbn phis phpr phps phtb pkls pkn pktp pky pkyt pkyu pky plsw pmsg pnul ppn ppn ppr pprn ppru ppr prec pscl pss psvc ptbb ptdm pthp punt rdef reopen 97 103 66 117 118 94 81 121 122 82 121 72 72 122 117 107 72 106 106 107 109 109 110 71 110 108 108 109 66 115 77 117 76 77 117 117 72 115 118 97 121 79 120 73 106 67

rprt rsim rtnm s2dt s2tm snul srow texp thdu tkey tm2s tnul tplt trec tscl ucrd ukls uky ukyu uky upch upck urlt vcks vers wldp xypx

66 105 68 95 95 115 92 93 69 96 95 115 67 96 115 72 114 71 72 114 96 94 68 94 65 84 85


Appendix B

Parameter De nitions
anynul array ascii binspec bitpix set to TRUE (=1) if any returned values are undefined, else FALSE array of numerical data values to read or write encoded checksum string the input table binning specifier 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. header record to be read or written (80 char max, null-terminated) CASESEN (=1) for case-sensitive string matching, else CASEINSEN (=0) grouping table "compact" option parameter. Allowed values are: OPT_CMT_MBR and OPT_CMT_MBR_DEL. name of the column (null-terminated) column number (first column = 1) the input file column specification used to delete, create, or rename table columns the keyword comment field (72 char max, null-terminated) should the checksum be complemented? type of coordinate projection (-SIN, -TAN, -ARC, -NCP, -GLS, -MER, or -AIT) 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.

card casesen cmopt colname colnum colspec

-

comment complm coordtypecpopt -

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
- number of groups in the primary array (usually = 1) - fitsfile* pointer to a grouping table HDU. - 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 gcount gfptr group


134
naxis naxis1 naxis2 naxis3 nchars nelementsnewfptr newveclennexc nfound nkeys ninc nmembers nmove nrows nstart nularray nulval nulstr numval offset openfptr outcolnumoutfile outfptr pcount repeat rmopt -

APPENDIX B. PARAMETER DEFINITIONS
number of dimensions in the FITS array length of the X/first axis of the FITS array length of the Y/second axis of the FITS array length of the Z/third axis of the FITS array number of characters to read or write number of data elements to read or write returned pointer to the reopened file new value for the column vector repeat parameter number of names in the exclusion list (may = 0) number of keywords found (highest keyword number) number of keywords in the sequence number of names in the inclusion list Number of grouping table members (NAXIS2 value). number of HDUs to move (+ or -), relative to current position number of rows in the table first integer value set to TRUE (=1) if corresponding data element is undefined numerical value to represent undefined pixels character string used to represent undefined values in ASCII table numerical data value, of the appropriate datatype byte offset in the heap to the first element of the vector pointer to a currently open FITS file output column number range = 1 to TFIELDS + 1 and optional output filename the input file will be copied to this prior to opening the file pointer to a 'fitsfile' structure describing the output FITS file. value of the PCOUNT keyword = size of binary table heap length of column vector (e.g. 12J) == 1 for ASCII table grouping table remove option parameter. Allowed values are: OPT_RM_GPT, OPT_RM_ENTRY, OPT_RM_MBR, and OPT_RM_ALL. root filename, minus any extension or filtering specifications celestial coordinate rotation angle (degrees) length of a table row, in characters or bytes sorted list of row numbers to be deleted from the table number of the row (first row = 1) - array of True/False results for each row that was evaluated linear scaling factor true value = (FITS value) * scale + zero second within minute (0 - 60.9999999999) (leapsecond!) TRUE (=1) if FITS file conforms to the Standard, else FALSE (=0) number of blank spaces to leave between ASCII table columns returned error status code (0 = OK) 32 bit unsigned checksum value byte position in row to start of column (1st col has tbcol = 1) Fortran style display format for the table column the value of the TDIMn keyword

rootname rot rowlen rowlist rownum row_status scale second simple space status sum tbcol tdisp tdimstr -


135
templt tfields tfopt tform - template string used in comparison (null-terminated) - number of fields (columns) in the table - grouping table member transfer option parameter. Allowed values are: OPT_MCP_ADD, and OPT_MCP_MOV. - 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.

- 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)

theap


136
ypix ypos yrefpix yrefval zero -

APPENDIX B. PARAMETER DEFINITIONS
y axis pixel location y axis celestial coordinate (usually DEC) (deg) Y axis reference pixel array location Y axis coordinate value at the reference pixel (deg) 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 (de ned in the le tsio.h) rather than the actual integer status values to improve the readability of their code.
Symbolic Const -------------Value ----0 SAME_FILE 101 TOO_MANY_FILES 103 FILE_NOT_OPENED 104 FILE_NOT_CREATED 105 WRITE_ERROR 106 END_OF_FILE 107 READ_ERROR 108 FILE_NOT_CLOSED 110 ARRAY_TOO_BIG 111 READONLY_FILE 112 MEMORY_ALLOCATION 113 BAD_FILEPTR 114 NULL_INPUT_PTR 115 SEEK_ERROR 116 BAD_URL_PREFIX TOO_MANY_DRIVERS DRIVER_INIT_FAILED NO_MATCHING_DRIVER URL_PARSE_ERROR SHARED_BADARG SHARED_NULPTR SHARED_TABFULL 121 122 123 124 125 Meaning ----------------------------------------OK, no error input and output files are the same tried to open too many FITS files at once could not open the named file could not create the named file error writing to FITS file tried to move past end of file error reading from FITS file could not close the file array dimensions exceed internal limit Cannot write to readonly file Could not allocate memory invalid fitsfile pointer NULL input pointer to routine error seeking position in file invalid URL prefix on file name tried to register too many IO drivers driver initialization failed matching driver is not registered failed to parse input file URL bad argument in shared memory driver null pointer passed as an argument no more free shared memory handles

151 152 153

137


138
SHARED_NOTINIT SHARED_IPCERR SHARED_NOMEM SHARED_AGAIN SHARED_NOFILE SHARED_NORESIZE HEADER_NOT_EMPTY KEY_NO_EXIST KEY_OUT_BOUNDS VALUE_UNDEFINED NO_QUOTE BAD_KEYCHAR BAD_ORDER NOT_POS_INT NO_END BAD_BITPIX BAD_NAXIS BAD_NAXES BAD_PCOUNT BAD_GCOUNT BAD_TFIELDS NEG_WIDTH NEG_ROWS COL_NOT_FOUND BAD_SIMPLE NO_SIMPLE NO_BITPIX NO_NAXIS NO_NAXES NO_XTENSION NOT_ATABLE NOT_BTABLE NO_PCOUNT NO_GCOUNT NO_TFIELDS NO_TBCOL NO_TFORM NOT_IMAGE BAD_TBCOL NOT_TABLE COL_TOO_WIDE COL_NOT_UNIQUE BAD_ROW_WIDTH UNKNOWN_EXT 154 155 156 157 158 159 201 202 203 204 205 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 241 251

APPENDIX C. CFITSIO ERROR STATUS CODES
shared memory driver is not initialized IPC error returned by a system call no memory in shared memory driver resource deadlock would occur attempt to open/create lock file failed shared memory block cannot be resized at the moment header already contains keywords keyword not found in header keyword record number is out of bounds keyword value field is blank string is missing the closing quote illegal character in keyword name or card required keywords out of order keyword value is not a positive integer couldn't find END keyword illegal BITPIX keyword value illegal NAXIS keyword value illegal NAXISn keyword value illegal PCOUNT keyword value illegal GCOUNT keyword value illegal TFIELDS keyword value negative table row size negative number of rows in table column with this name not found in table illegal value of SIMPLE keyword Primary array doesn't start with SIMPLE Second keyword not BITPIX Third keyword not NAXIS Couldn't find all the NAXISn keywords HDU doesn't start with XTENSION keyword the CHDU is not an ASCII table extension the CHDU is not a binary table extension couldn't find PCOUNT keyword couldn't find GCOUNT keyword couldn't find TFIELDS keyword couldn't find TBCOLn keyword couldn't find TFORMn keyword the CHDU is not an IMAGE extension TBCOLn keyword value < 0 or > rowlength the CHDU is not a table column is too wide to fit in table more than 1 column name matches template sum of column widths not = NAXIS1 unrecognizable FITS extension type


139
UNKNOWN_REC END_JUNK BAD_HEADER_FILL BAD_DATA_FILL BAD_TFORM BAD_TFORM_DTYPE BAD_TDIM BAD_HDU_NUM BAD_COL_NUM NEG_FILE_POS NEG_BYTES BAD_ROW_NUM BAD_ELEM_NUM NOT_ASCII_COL NOT_LOGICAL_COL BAD_ATABLE_FORMAT BAD_BTABLE_FORMAT NO_NULL NOT_VARI_LEN BAD_DIMEN BAD_PIX_NUM ZERO_SCALE NEG_AXIS 252 253 254 255 261 262 263 301 302 304 306 307 308 309 310 311 312 314 317 320 321 322 323 unknown record 1st keyword not SIMPLE or XTENSION END keyword is not blank Header fill area contains non-blank chars Illegal data fill bytes (not zero or blank) illegal TFORM format code unrecognizable TFORM datatype code illegal TDIMn keyword value HDU number < 1 or > MAXHDU column number < 1 or > tfields tried to move to negative byte location in file tried to read or write negative number of bytes illegal starting row number in table illegal starting element number in vector this is not an ASCII string column this is not a logical datatype column ASCII table column has wrong format Binary table column has wrong format null value has not been defined this is not a variable length column illegal number of dimensions in array first pixel number greater than last pixel illegal BSCALE or TSCALn keyword = 0 illegal axis length < 1 340 341 342 343 344 345 346 347 348 360 361 362 Grouping function error

NOT_GROUP_TABLE HDU_ALREADY_MEMBER MEMBER_NOT_FOUND GROUP_NOT_FOUND BAD_GROUP_ID TOO_MANY_HDUS_TRACKED HDU_ALREADY_TRACKED BAD_OPTION IDENTICAL_POINTERS NGP_NO_MEMORY NGP_READ_ERR NGP_NUL_PTR

NGP_EMPTY_CURLINE

363

NGP_UNREAD_QUEUE_FULL 364 NGP_INC_NESTING 365

malloc failed read error from file null pointer passed as an argument. Passing null pointer as a name of template file raises this error line read seems to be empty (used internally) cannot unread more then 1 line (or single line twice) too deep include file nesting (infinite


140
NGP_ERR_FOPEN NGP_EOF NGP_BAD_ARG NGP_TOKEN_NOT_EXPECT 366 367 368 369

APPENDIX C. CFITSIO ERROR STATUS CODES
loop, template includes itself ?) fopen() failed, cannot open template file end of file encountered and not expected bad arguments passed. Usually means internal parser error. Should not happen 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 PARSE_SYNTAX_ERR PARSE_BAD_TYPE PARSE_LRG_VECTOR PARSE_NO_OUTPUT PARSE_BAD_COL PARSE_BAD_OUTPUT ANGLE_TOO_BIG BAD_WCS_VAL WCS_ERROR BAD_WCS_PROJ NO_WCS_KEY APPROX_WCS_KEY 420 431 432 433 434 435 436 501 502 503 504 505 506 error in date or time conversion syntax error in parser expression expression did not evaluate to desired type vector result too large to return in array data parser failed not sent an out column bad data encounter while parsing column Output file not of proper type celestial angle too large for projection bad celestial coordinate or pixel value error in celestial coordinate calculation unsupported type of celestial projection celestial coordinate keywords not found approximate wcs keyword values were returned