1 /*============================================================================
2   WCSLIB 7.3 - an implementation of the FITS WCS standard.
3   Copyright (C) 1995-2020, Mark Calabretta
4 
5   This file is part of WCSLIB.
6 
7   WCSLIB is free software: you can redistribute it and/or modify it under the
8   terms of the GNU Lesser General Public License as published by the Free
9   Software Foundation, either version 3 of the License, or (at your option)
10   any later version.
11 
12   WCSLIB is distributed in the hope that it will be useful, but WITHOUT ANY
13   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14   FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
15   more details.
16 
17   You should have received a copy of the GNU Lesser General Public License
18   along with WCSLIB.  If not, see http://www.gnu.org/licenses.
19 
20   Direct correspondence concerning WCSLIB to mark@calabretta.id.au
21 
22   Author: Mark Calabretta, Australia Telescope National Facility, CSIRO.
23   http://www.atnf.csiro.au/people/Mark.Calabretta
24   $Id: wcshdr.h,v 7.3.1.2 2020/08/17 11:19:09 mcalabre Exp mcalabre $
25 *=============================================================================
26 *
27 * WCSLIB 7.3 - C routines that implement the FITS World Coordinate System
28 * (WCS) standard.  Refer to the README file provided with WCSLIB for an
29 * overview of the library.
30 *
31 *
32 * Summary of the wcshdr routines
33 * ------------------------------
34 * Routines in this suite are aimed at extracting WCS information from a FITS
35 * file.  The information is encoded via keywords defined in
36 *
37 =   "Representations of world coordinates in FITS",
38 =   Greisen, E.W., & Calabretta, M.R. 2002, A&A, 395, 1061 (WCS Paper I)
39 =
40 =   "Representations of celestial coordinates in FITS",
41 =   Calabretta, M.R., & Greisen, E.W. 2002, A&A, 395, 1077 (WCS Paper II)
42 =
43 =   "Representations of spectral coordinates in FITS",
44 =   Greisen, E.W., Calabretta, M.R., Valdes, F.G., & Allen, S.L.
45 =   2006, A&A, 446, 747 (WCS Paper III)
46 =
47 =   "Representations of distortions in FITS world coordinate systems",
48 =   Calabretta, M.R. et al. (WCS Paper IV, draft dated 2004/04/22),
49 =   available from http://www.atnf.csiro.au/people/Mark.Calabretta
50 =
51 =   "Representations of time coordinates in FITS -
52 =    Time and relative dimension in space",
53 =   Rots, A.H., Bunclark, P.S., Calabretta, M.R., Allen, S.L.,
54 =   Manchester, R.N., & Thompson, W.T. 2015, A&A, 574, A36 (WCS Paper VII)
55 *
56 * These routines provide the high-level interface between the FITS file and
57 * the WCS coordinate transformation routines.
58 *
59 * Additionally, function wcshdo() is provided to write out the contents of a
60 * wcsprm struct as a FITS header.
61 *
62 * Briefly, the anticipated sequence of operations is as follows:
63 *
64 *   - 1: Open the FITS file and read the image or binary table header, e.g.
65 *        using CFITSIO routine fits_hdr2str().
66 *
67 *   - 2: Parse the header using wcspih() or wcsbth(); they will automatically
68 *        interpret 'TAB' header keywords using wcstab().
69 *
70 *   - 3: Allocate memory for, and read 'TAB' arrays from the binary table
71 *        extension, e.g. using CFITSIO routine fits_read_wcstab() - refer to
72 *        the prologue of getwcstab.h.  wcsset() will automatically take
73 *        control of this allocated memory, in particular causing it to be
74 *        freed by wcsfree().
75 *
76 *   - 4: Translate non-standard WCS usage using wcsfix(), see wcsfix.h.
77 *
78 *   - 5: Initialize wcsprm struct(s) using wcsset() and calculate coordinates
79 *        using wcsp2s() and/or wcss2p().  Refer to the prologue of wcs.h for a
80 *        description of these and other high-level WCS coordinate
81 *        transformation routines.
82 *
83 *   - 6: Clean up by freeing memory with wcsvfree().
84 *
85 * In detail:
86 *
87 * - wcspih() is a high-level FITS WCS routine that parses an image header.  It
88 *   returns an array of up to 27 wcsprm structs on each of which it invokes
89 *   wcstab().
90 *
91 * - wcsbth() is the analogue of wcspih() for use with binary tables; it
92 *   handles image array and pixel list keywords.  As an extension of the FITS
93 *   WCS standard, it also recognizes image header keywords which may be used
94 *   to provide default values via an inheritance mechanism.
95 *
96 * - wcstab() assists in filling in members of the wcsprm struct associated
97 *   with coordinate lookup tables ('TAB').  These are based on arrays stored
98 *   in a FITS binary table extension (BINTABLE) that are located by PVi_ma
99 *   keywords in the image header.
100 *
101 * - wcsidx() and wcsbdx() are utility routines that return the index for a
102 *   specified alternate coordinate descriptor in the array of wcsprm structs
103 *   returned by wcspih() or wcsbth().
104 *
105 * - wcsvfree() deallocates memory for an array of wcsprm structs, such as
106 *   returned by wcspih() or wcsbth().
107 *
108 * - wcshdo() writes out a wcsprm struct as a FITS header.
109 *
110 *
111 * wcspih() - FITS WCS parser routine for image headers
112 * ----------------------------------------------------
113 * wcspih() is a high-level FITS WCS routine that parses an image header,
114 * either that of a primary HDU or of an image extension.  All WCS keywords
115 * defined in Papers I, II, III, IV, and VII are recognized, and also those
116 * used by the AIPS convention and certain other keywords that existed in early
117 * drafts of the WCS papers as explained in wcsbth() note 5.  wcspih() also
118 * handles keywords associated with non-standard distortion functions described
119 * in the prologue of dis.h.
120 *
121 * Given a character array containing a FITS image header, wcspih() identifies
122 * and reads all WCS keywords for the primary coordinate representation and up
123 * to 26 alternate representations.  It returns this information as an array of
124 * wcsprm structs.
125 *
126 * wcspih() invokes wcstab() on each of the wcsprm structs that it returns.
127 *
128 * Use wcsbth() in preference to wcspih() for FITS headers of unknown type;
129 * wcsbth() can parse image headers as well as binary table and pixel list
130 * headers, although it cannot handle keywords relating to distortion
131 * functions, which may only exist in a primary image header.
132 *
133 * Given and returned:
134 *   header    char[]    Character array containing the (entire) FITS image
135 *                       header from which to identify and construct the
136 *                       coordinate representations, for example, as might be
137 *                       obtained conveniently via the CFITSIO routine
138 *                       fits_hdr2str().
139 *
140 *                       Each header "keyrecord" (formerly "card image")
141 *                       consists of exactly 80 7-bit ASCII printing characters
142 *                       in the range 0x20 to 0x7e (which excludes NUL, BS,
143 *                       TAB, LF, FF and CR) especially noting that the
144 *                       keyrecords are NOT null-terminated.
145 *
146 *                       For negative values of ctrl (see below), header[] is
147 *                       modified so that WCS keyrecords processed by wcspih()
148 *                       are removed from it.
149 *
150 * Given:
151 *   nkeyrec   int       Number of keyrecords in header[].
152 *
153 *   relax     int       Degree of permissiveness:
154 *                         0: Recognize only FITS keywords defined by the
155 *                            published WCS standard.
156 *                         WCSHDR_all: Admit all recognized informal
157 *                            extensions of the WCS standard.
158 *                       Fine-grained control of the degree of permissiveness
159 *                       is also possible as explained in wcsbth() note 5.
160 *
161 *   ctrl      int       Error reporting and other control options for invalid
162 *                       WCS and other header keyrecords:
163 *                           0: Do not report any rejected header keyrecords.
164 *                           1: Produce a one-line message stating the number
165 *                              of WCS keyrecords rejected (nreject).
166 *                           2: Report each rejected keyrecord and the reason
167 *                              why it was rejected.
168 *                           3: As above, but also report all non-WCS
169 *                              keyrecords that were discarded, and the number
170 *                              of coordinate representations (nwcs) found.
171 *                           4: As above, but also report the accepted WCS
172 *                              keyrecords, with a summary of the number
173 *                              accepted as well as rejected.
174 *                       The report is written to stderr by default, or the
175 *                       stream set by wcsprintf_set().
176 *
177 *                       For ctrl < 0, WCS keyrecords processed by wcspih()
178 *                       are removed from header[]:
179 *                          -1: Remove only valid WCS keyrecords whose values
180 *                              were successfully extracted, nothing is
181 *                              reported.
182 *                          -2: As above, but also remove WCS keyrecords that
183 *                              were rejected, reporting each one and the
184 *                              reason that it was rejected.
185 *                          -3: As above, and also report the number of
186 *                              coordinate representations (nwcs) found.
187 *                         -11: Same as -1 but preserving global WCS-related
188 *                              keywords such as '{DATE,MJD}-{OBS,BEG,AVG,END}'
189 *                              and the other basic time-related keywords, and
190 *                              'OBSGEO-{X,Y,Z,L,B,H}'.
191 *                       If any keyrecords are removed from header[] it will
192 *                       be null-terminated (NUL not being a legal FITS header
193 *                       character), otherwise it will contain its original
194 *                       complement of nkeyrec keyrecords and possibly not be
195 *                       null-terminated.
196 *
197 * Returned:
198 *   nreject   int*      Number of WCS keywords rejected for syntax errors,
199 *                       illegal values, etc.  Keywords not recognized as WCS
200 *                       keywords are simply ignored.  Refer also to wcsbth()
201 *                       note 5.
202 *
203 *   nwcs      int*      Number of coordinate representations found.
204 *
205 *   wcs       struct wcsprm**
206 *                       Pointer to an array of wcsprm structs containing up to
207 *                       27 coordinate representations.
208 *
209 *                       Memory for the array is allocated by wcspih() which
210 *                       also invokes wcsini() for each struct to allocate
211 *                       memory for internal arrays and initialize their
212 *                       members to default values.  Refer also to wcsbth()
213 *                       note 8.  Note that wcsset() is not invoked on these
214 *                       structs.
215 *
216 *                       This allocated memory must be freed by the user, first
217 *                       by invoking wcsfree() for each struct, and then by
218 *                       freeing the array itself.  A routine, wcsvfree(), is
219 *                       provided to do this (see below).
220 *
221 * Function return value:
222 *             int       Status return value:
223 *                         0: Success.
224 *                         1: Null wcsprm pointer passed.
225 *                         2: Memory allocation failed.
226 *                         4: Fatal error returned by Flex parser.
227 *
228 * Notes:
229 *   Refer to wcsbth() notes 1, 2, 3, 5, 7, and 8.
230 *
231 *
232 * wcsbth() - FITS WCS parser routine for binary table and image headers
233 * ---------------------------------------------------------------------
234 * wcsbth() is a high-level FITS WCS routine that parses a binary table header.
235 * It handles image array and pixel list WCS keywords which may be present
236 * together in one header.
237 *
238 * As an extension of the FITS WCS standard, wcsbth() also recognizes image
239 * header keywords in a binary table header.  These may be used to provide
240 * default values via an inheritance mechanism discussed in note 5 (c.f.
241 * WCSHDR_AUXIMG and WCSHDR_ALLIMG), or may instead result in wcsprm structs
242 * that are not associated with any particular column.  Thus wcsbth() can
243 * handle primary image and image extension headers in addition to binary table
244 * headers (it ignores NAXIS and does not rely on the presence of the TFIELDS
245 * keyword).
246 *
247 * All WCS keywords defined in Papers I, II, III, and VII are recognized, and
248 * also those used by the AIPS convention and certain other keywords that
249 * existed in early drafts of the WCS papers as explained in note 5 below.
250 *
251 * wcsbth() sets the colnum or colax[] members of the wcsprm structs that it
252 * returns with the column number of an image array or the column numbers
253 * associated with each pixel coordinate element in a pixel list.  wcsprm
254 * structs that are not associated with any particular column, as may be
255 * derived from image header keywords, have colnum == 0.
256 *
257 * Note 6 below discusses the number of wcsprm structs returned by wcsbth(),
258 * and the circumstances in which image header keywords cause a struct to be
259 * created.  See also note 9 concerning the number of separate images that may
260 * be stored in a pixel list.
261 *
262 * The API to wcsbth() is similar to that of wcspih() except for the addition
263 * of extra arguments that may be used to restrict its operation.  Like
264 * wcspih(), wcsbth() invokes wcstab() on each of the wcsprm structs that it
265 * returns.
266 *
267 * Given and returned:
268 *   header    char[]    Character array containing the (entire) FITS binary
269 *                       table, primary image, or image extension header from
270 *                       which to identify and construct the coordinate
271 *                       representations, for example, as might be obtained
272 *                       conveniently via the CFITSIO routine fits_hdr2str().
273 *
274 *                       Each header "keyrecord" (formerly "card image")
275 *                       consists of exactly 80 7-bit ASCII printing
276 *                       characters in the range 0x20 to 0x7e (which excludes
277 *                       NUL, BS, TAB, LF, FF and CR) especially noting that
278 *                       the keyrecords are NOT null-terminated.
279 *
280 *                       For negative values of ctrl (see below), header[] is
281 *                       modified so that WCS keyrecords processed by wcsbth()
282 *                       are removed from it.
283 *
284 * Given:
285 *   nkeyrec   int       Number of keyrecords in header[].
286 *
287 *   relax     int       Degree of permissiveness:
288 *                         0: Recognize only FITS keywords defined by the
289 *                            published WCS standard.
290 *                         WCSHDR_all: Admit all recognized informal
291 *                            extensions of the WCS standard.
292 *                       Fine-grained control of the degree of permissiveness
293 *                       is also possible, as explained in note 5 below.
294 *
295 *   ctrl      int       Error reporting and other control options for invalid
296 *                       WCS and other header keyrecords:
297 *                           0: Do not report any rejected header keyrecords.
298 *                           1: Produce a one-line message stating the number
299 *                              of WCS keyrecords rejected (nreject).
300 *                           2: Report each rejected keyrecord and the reason
301 *                              why it was rejected.
302 *                           3: As above, but also report all non-WCS
303 *                              keyrecords that were discarded, and the number
304 *                              of coordinate representations (nwcs) found.
305 *                           4: As above, but also report the accepted WCS
306 *                              keyrecords, with a summary of the number
307 *                              accepted as well as rejected.
308 *                       The report is written to stderr by default, or the
309 *                       stream set by wcsprintf_set().
310 *
311 *                       For ctrl < 0, WCS keyrecords processed by wcsbth()
312 *                       are removed from header[]:
313 *                          -1: Remove only valid WCS keyrecords whose values
314 *                              were successfully extracted, nothing is
315 *                              reported.
316 *                          -2: Also remove WCS keyrecords that were rejected,
317 *                              reporting each one and the reason that it was
318 *                              rejected.
319 *                          -3: As above, and also report the number of
320 *                              coordinate representations (nwcs) found.
321 *                         -11: Same as -1 but preserving global WCS-related
322 *                              keywords such as '{DATE,MJD}-{OBS,BEG,AVG,END}'
323 *                              and the other basic time-related keywords, and
324 *                              'OBSGEO-{X,Y,Z,L,B,H}'.
325 *                       If any keyrecords are removed from header[] it will
326 *                       be null-terminated (NUL not being a legal FITS header
327 *                       character), otherwise it will contain its original
328 *                       complement of nkeyrec keyrecords and possibly not be
329 *                       null-terminated.
330 *
331 *   keysel    int       Vector of flag bits that may be used to restrict the
332 *                       keyword types considered:
333 *                         WCSHDR_IMGHEAD: Image header keywords.
334 *                         WCSHDR_BIMGARR: Binary table image array.
335 *                         WCSHDR_PIXLIST: Pixel list keywords.
336 *                       If zero, there is no restriction.
337 *
338 *                       Keywords such as EQUIna or RFRQna that are common to
339 *                       binary table image arrays and pixel lists (including
340 *                       WCSNna and TWCSna, as explained in note 4 below) are
341 *                       selected by both WCSHDR_BIMGARR and WCSHDR_PIXLIST.
342 *                       Thus if inheritance via WCSHDR_ALLIMG is enabled as
343 *                       discussed in note 5 and one of these shared keywords
344 *                       is present, then WCSHDR_IMGHEAD and WCSHDR_PIXLIST
345 *                       alone may be sufficient to cause the construction of
346 *                       coordinate descriptions for binary table image arrays.
347 *
348 *   colsel    int*      Pointer to an array of table column numbers used to
349 *                       restrict the keywords considered by wcsbth().
350 *
351 *                       A null pointer may be specified to indicate that there
352 *                       is no restriction.  Otherwise, the magnitude of
353 *                       cols[0] specifies the length of the array:
354 *                         cols[0] > 0: the columns are included,
355 *                         cols[0] < 0: the columns are excluded.
356 *
357 *                       For the pixel list keywords TPn_ka and TCn_ka (and
358 *                       TPCn_ka and TCDn_ka if WCSHDR_LONGKEY is enabled), it
359 *                       is an error for one column to be selected but not the
360 *                       other.  This is unlike the situation with invalid
361 *                       keyrecords, which are simply rejected, because the
362 *                       error is not intrinsic to the header itself but
363 *                       arises in the way that it is processed.
364 *
365 * Returned:
366 *   nreject   int*      Number of WCS keywords rejected for syntax errors,
367 *                       illegal values, etc.  Keywords not recognized as WCS
368 *                       keywords are simply ignored, refer also to note 5
369 *                       below.
370 *
371 *   nwcs      int*      Number of coordinate representations found.
372 *
373 *   wcs       struct wcsprm**
374 *                       Pointer to an array of wcsprm structs containing up
375 *                       to 27027 coordinate representations, refer to note 6
376 *                       below.
377 *
378 *                       Memory for the array is allocated by wcsbth() which
379 *                       also invokes wcsini() for each struct to allocate
380 *                       memory for internal arrays and initialize their
381 *                       members to default values.  Refer also to note 8
382 *                       below.  Note that wcsset() is not invoked on these
383 *                       structs.
384 *
385 *                       This allocated memory must be freed by the user, first
386 *                       by invoking wcsfree() for each struct, and then by
387 *                       freeing the array itself.  A routine, wcsvfree(), is
388 *                       provided to do this (see below).
389 *
390 * Function return value:
391 *             int       Status return value:
392 *                         0: Success.
393 *                         1: Null wcsprm pointer passed.
394 *                         2: Memory allocation failed.
395 *                         3: Invalid column selection.
396 *                         4: Fatal error returned by Flex parser.
397 *
398 * Notes:
399 *   1: wcspih() determines the number of coordinate axes independently for
400 *      each alternate coordinate representation (denoted by the "a" value in
401 *      keywords like CTYPEia) from the higher of
402 *
403 *        a: NAXIS,
404 *        b: WCSAXESa,
405 *        c: The highest axis number in any parameterized WCS keyword.  The
406 *           keyvalue, as well as the keyword, must be syntactically valid
407 *           otherwise it will not be considered.
408 *
409 *      If none of these keyword types is present, i.e. if the header only
410 *      contains auxiliary WCS keywords for a particular coordinate
411 *      representation, then no coordinate description is constructed for it.
412 *
413 *      wcsbth() is similar except that it ignores the NAXIS keyword if given
414 *      an image header to process.
415 *
416 *      The number of axes, which is returned as a member of the wcsprm
417 *      struct, may differ for different coordinate representations of the
418 *      same image.
419 *
420 *   2: wcspih() and wcsbth() enforce correct FITS "keyword = value" syntax
421 *      with regard to "= " occurring in columns 9 and 10.
422 *
423 *      However, they do recognize free-format character (NOST 100-2.0,
424 *      Sect. 5.2.1), integer (Sect. 5.2.3), and floating-point values
425 *      (Sect. 5.2.4) for all keywords.
426 *
427 *   3: Where CROTAn, CDi_ja, and PCi_ja occur together in one header wcspih()
428 *      and wcsbth() treat them as described in the prologue to wcs.h.
429 *
430 *   4: WCS Paper I mistakenly defined the pixel list form of WCSNAMEa as
431 *      TWCSna instead of WCSNna; the 'T' is meant to substitute for the axis
432 *      number in the binary table form of the keyword - note that keywords
433 *      defined in WCS Papers II, III, and VII that are not parameterized by
434 *      axis number have identical forms for binary tables and pixel lists.
435 *      Consequently wcsbth() always treats WCSNna and TWCSna as equivalent.
436 *
437 *   5: wcspih() and wcsbth() interpret the "relax" argument as a vector of
438 *      flag bits to provide fine-grained control over what non-standard WCS
439 *      keywords to accept.  The flag bits are subject to change in future and
440 *      should be set by using the preprocessor macros (see below) for the
441 *      purpose.
442 *
443 *      - WCSHDR_none: Don't accept any extensions (not even those in the
444 *              errata).  Treat non-conformant keywords in the same way as
445 *              non-WCS keywords in the header, i.e. simply ignore them.
446 *
447 *      - WCSHDR_all: Accept all extensions recognized by the parser.
448 *
449 *      - WCSHDR_reject: Reject non-standard keyrecords (that are not otherwise
450 *              explicitly accepted by one of the flags below).  A message will
451 *              optionally be printed on stderr by default, or the stream set
452 *              by wcsprintf_set(), as determined by the ctrl argument, and
453 *              nreject will be incremented.
454 *
455 *              This flag may be used to signal the presence of non-standard
456 *              keywords, otherwise they are simply passed over as though they
457 *              did not exist in the header.  It is mainly intended for testing
458 *              conformance of a FITS header to the WCS standard.
459 *
460 *              Keyrecords may be non-standard in several ways:
461 *
462 *                - The keyword may be syntactically valid but with keyvalue of
463 *                  incorrect type or invalid syntax, or the keycomment may be
464 *                  malformed.
465 *
466 *                - The keyword may strongly resemble a WCS keyword but not, in
467 *                  fact, be one because it does not conform to the standard.
468 *                  For example, "CRPIX01" looks like a CRPIXja keyword, but in
469 *                  fact the leading zero on the axis number violates the basic
470 *                  FITS standard.  Likewise, "LONPOLE2" is not a valid
471 *                  LONPOLEa keyword in the WCS standard, and indeed there is
472 *                  nothing the parser can sensibly do with it.
473 *
474 *                - Use of the keyword may be deprecated by the standard.  Such
475 *                  will be rejected if not explicitly accepted via one of the
476 *                  flags below.
477 *
478 *      - WCSHDR_strict: As for WCSHDR_reject, but also reject AIPS-convention
479 *              keywords and all other deprecated usage that is not explicitly
480 *              accepted.
481 *
482 *      - WCSHDR_CROTAia: Accept CROTAia (wcspih()),
483 *                               iCROTna (wcsbth()),
484 *                               TCROTna (wcsbth()).
485 *      - WCSHDR_VELREFa: Accept VELREFa.
486 *              wcspih() always recognizes the AIPS-convention keywords,
487 *              CROTAn, EPOCH, and VELREF for the primary representation
488 *              (a = ' ') but alternates are non-standard.
489 *
490 *              wcsbth() accepts EPOCHa and VELREFa only if WCSHDR_AUXIMG is
491 *              also enabled.
492 *
493 *      - WCSHDR_CD00i00j: Accept CD00i00j (wcspih()).
494 *      - WCSHDR_PC00i00j: Accept PC00i00j (wcspih()).
495 *      - WCSHDR_PROJPn:   Accept PROJPn   (wcspih()).
496 *              These appeared in early drafts of WCS Paper I+II (before they
497 *              were split) and are equivalent to CDi_ja, PCi_ja, and PVi_ma
498 *              for the primary representation (a = ' ').  PROJPn is
499 *              equivalent to PVi_ma with m = n <= 9, and is associated
500 *              exclusively with the latitude axis.
501 *
502 *      - WCSHDR_CD0i_0ja: Accept CD0i_0ja (wcspih()).
503 *      - WCSHDR_PC0i_0ja: Accept PC0i_0ja (wcspih()).
504 *      - WCSHDR_PV0i_0ma: Accept PV0i_0ja (wcspih()).
505 *      - WCSHDR_PS0i_0ma: Accept PS0i_0ja (wcspih()).
506 *              Allow the numerical index to have a leading zero in doubly-
507 *              parameterized keywords, for example, PC01_01.  WCS Paper I
508 *              (Sects 2.1.2 & 2.1.4) explicitly disallows leading zeroes.
509 *              The FITS 3.0 standard document (Sect. 4.1.2.1) states that the
510 *              index in singly-parameterized keywords (e.g. CTYPEia) "shall
511 *              not have leading zeroes", and later in Sect. 8.1 that "leading
512 *              zeroes must not be used" on PVi_ma and PSi_ma.  However, by an
513 *              oversight, it is silent on PCi_ja and CDi_ja.
514 *
515 *      - WCSHDR_DOBSn (wcsbth() only): Allow DOBSn, the column-specific
516 *              analogue of DATE-OBS.  By an oversight this was never formally
517 *              defined in the standard.
518 *
519 *      - WCSHDR_OBSGLBHn (wcsbth() only): Allow OBSGLn, OBSGBn, and OBSGHn,
520 *              the column-specific analogues of OBSGEO-L, OBSGEO-B, and
521 *              OBSGEO-H.  By an oversight these were never formally defined in
522 *              the standard.
523 *
524 *      - WCSHDR_RADECSYS: Accept RADECSYS.  This appeared in early drafts of
525 *              WCS Paper I+II and was subsequently replaced by RADESYSa.
526 *
527 *              wcsbth() accepts RADECSYS only if WCSHDR_AUXIMG is also
528 *              enabled.
529 *
530 *      - WCSHDR_EPOCHa:  Accept EPOCHa.
531 *
532 *      - WCSHDR_VSOURCE: Accept VSOURCEa or VSOUna (wcsbth()).  This appeared
533 *              in early drafts of WCS Paper III and was subsequently dropped
534 *              in favour of ZSOURCEa and ZSOUna.
535 *
536 *              wcsbth() accepts VSOURCEa only if WCSHDR_AUXIMG is also
537 *              enabled.
538 *
539 *      - WCSHDR_DATEREF: Accept DATE-REF, MJD-REF, MJD-REFI, MJD-REFF, JDREF,
540 *              JD-REFI, and JD-REFF as synonyms for the standard keywords,
541 *              DATEREF, MJDREF, MJDREFI, MJDREFF, JDREF, JDREFI, and JDREFF.
542 *              The latter buck the pattern set by the other date keywords
543 *              ({DATE,MJD}-{OBS,BEG,AVG,END}), thereby increasing the
544 *              potential for confusion and error.
545 *
546 *      - WCSHDR_LONGKEY (wcsbth() only): Accept long forms of the alternate
547 *              binary table and pixel list WCS keywords, i.e. with "a" non-
548 *              blank.  Specifically
549 *
550 #                jCRPXna  TCRPXna  :  jCRPXn  jCRPna  TCRPXn  TCRPna  CRPIXja
551 #                   -     TPCn_ka  :    -     ijPCna    -     TPn_ka  PCi_ja
552 #                   -     TCDn_ka  :    -     ijCDna    -     TCn_ka  CDi_ja
553 #                iCDLTna  TCDLTna  :  iCDLTn  iCDEna  TCDLTn  TCDEna  CDELTia
554 #                iCUNIna  TCUNIna  :  iCUNIn  iCUNna  TCUNIn  TCUNna  CUNITia
555 #                iCTYPna  TCTYPna  :  iCTYPn  iCTYna  TCTYPn  TCTYna  CTYPEia
556 #                iCRVLna  TCRVLna  :  iCRVLn  iCRVna  TCRVLn  TCRVna  CRVALia
557 #                iPVn_ma  TPVn_ma  :    -     iVn_ma    -     TVn_ma  PVi_ma
558 #                iPSn_ma  TPSn_ma  :    -     iSn_ma    -     TSn_ma  PSi_ma
559 *
560 *              where the primary and standard alternate forms together with
561 *              the image-header equivalent are shown rightwards of the colon.
562 *
563 *              The long form of these keywords could be described as quasi-
564 *              standard.  TPCn_ka, iPVn_ma, and TPVn_ma appeared by mistake
565 *              in the examples in WCS Paper II and subsequently these and
566 *              also TCDn_ka, iPSn_ma and TPSn_ma were legitimized by the
567 *              errata to the WCS papers.
568 *
569 *              Strictly speaking, the other long forms are non-standard and
570 *              in fact have never appeared in any draft of the WCS papers nor
571 *              in the errata.  However, as natural extensions of the primary
572 *              form they are unlikely to be written with any other intention.
573 *              Thus it should be safe to accept them provided, of course,
574 *              that the resulting keyword does not exceed the 8-character
575 *              limit.
576 *
577 *              If WCSHDR_CNAMn is enabled then also accept
578 *
579 #                iCNAMna  TCNAMna  :   ---   iCNAna    ---   TCNAna  CNAMEia
580 #                iCRDEna  TCRDEna  :   ---   iCRDna    ---   TCRDna  CRDERia
581 #                iCSYEna  TCSYEna  :   ---   iCSYna    ---   TCSYna  CSYERia
582 #                iCZPHna  TCZPHna  :   ---   iCZPna    ---   TCZPna  CZPHSia
583 #                iCPERna  TCPERna  :   ---   iCPRna    ---   TCPRna  CPERIia
584 *
585 *              Note that CNAMEia, CRDERia, CSYERia, CZPHSia, CPERIia, and
586 *              their variants are not used by WCSLIB but are stored in the
587 *              wcsprm struct as auxiliary information.
588 *
589 *      - WCSHDR_CNAMn (wcsbth() only): Accept iCNAMn, iCRDEn, iCSYEn, iCZPHn,
590 *              iCPERn, TCNAMn, TCRDEn, TCSYEn, TCZPHn, and TCPERn, i.e. with
591 *              "a" blank.  While non-standard, these are the obvious analogues
592 *              of iCTYPn, TCTYPn, etc.
593 *
594 *      - WCSHDR_AUXIMG (wcsbth() only): Allow the image-header form of an
595 *              auxiliary WCS keyword with representation-wide scope to
596 *              provide a default value for all images.  This default may be
597 *              overridden by the column-specific form of the keyword.
598 *
599 *              For example, a keyword like EQUINOXa would apply to all image
600 *              arrays in a binary table, or all pixel list columns with
601 *              alternate representation "a" unless overridden by EQUIna.
602 *
603 *              Specifically the keywords are:
604 *
605 #                LONPOLEa  for LONPna
606 #                LATPOLEa  for LATPna
607 #                VELREF        -       ... (No column-specific form.)
608 #                VELREFa       -       ... Only if WCSHDR_VELREFa is set.
609 *
610 *              whose keyvalues are actually used by WCSLIB, and also keywords
611 *              providing auxiliary information that is simply stored in the
612 *              wcsprm struct:
613 *
614 #                WCSNAMEa  for WCSNna  ... Or TWCSna (see below).
615 #
616 #                DATE-OBS  for DOBSn
617 #                MJD-OBS   for MJDOBn
618 #
619 #                RADESYSa  for RADEna
620 #                RADECSYS  for RADEna  ... Only if WCSHDR_RADECSYS is set.
621 #                EPOCH         -       ... (No column-specific form.)
622 #                EPOCHa        -       ... Only if WCSHDR_EPOCHa is set.
623 #                EQUINOXa  for EQUIna
624 *
625 *              where the image-header keywords on the left provide default
626 *              values for the column specific keywords on the right.
627 *
628 *              Note that, according to Sect. 8.1 of WCS Paper III, and
629 *              Sect. 5.2 of WCS Paper VII, the following are always inherited:
630 *
631 #                RESTFREQ  for RFRQna
632 #                RESTFRQa  for RFRQna
633 #                RESTWAVa  for RWAVna
634 *
635 *              being those actually used by WCSLIB, together with the
636 *              following auxiliary keywords, many of which do not have binary
637 *              table equivalents and therefore can only be inherited:
638 *
639 #                TIMESYS       -
640 #                TREFPOS   for TRPOSn
641 #                TREFDIR   for TRDIRn
642 #                PLEPHEM       -
643 #                TIMEUNIT      -
644 #                DATEREF       -
645 #                MJDREF        -
646 #                MJDREFI       -
647 #                MJDREFF       -
648 #                JDREF         -
649 #                JDREFI        -
650 #                JDREFF        -
651 #                TIMEOFFS      -
652 #
653 #                DATE-BEG      -
654 #                DATE-AVG  for DAVGn
655 #                DATE-END      -
656 #                MJD-BEG       -
657 #                MJD-AVG   for MJDAn
658 #                MJD-END       -
659 #                JEPOCH        -
660 #                BEPOCH        -
661 #                TSTART        -
662 #                TSTOP         -
663 #                XPOSURE       -
664 #                TELAPSE       -
665 #
666 #                TIMSYER       -
667 #                TIMRDER       -
668 #                TIMEDEL       -
669 #                TIMEPIXR      -
670 #
671 #                OBSGEO-X  for OBSGXn
672 #                OBSGEO-Y  for OBSGYn
673 #                OBSGEO-Z  for OBSGZn
674 #                OBSGEO-L  for OBSGLn
675 #                OBSGEO-B  for OBSGBn
676 #                OBSGEO-H  for OBSGHn
677 #                OBSORBIT      -
678 #
679 #                SPECSYSa  for SPECna
680 #                SSYSOBSa  for SOBSna
681 #                VELOSYSa  for VSYSna
682 #                VSOURCEa  for VSOUna  ... Only if WCSHDR_VSOURCE is set.
683 #                ZSOURCEa  for ZSOUna
684 #                SSYSSRCa  for SSRCna
685 #                VELANGLa  for VANGna
686 *
687 *              Global image-header keywords, such as MJD-OBS, apply to all
688 *              alternate representations, and would therefore provide a
689 *              default value for all images in the header.
690 *
691 *              This auxiliary inheritance mechanism applies to binary table
692 *              image arrays and pixel lists alike.  Most of these keywords
693 *              have no default value, the exceptions being LONPOLEa and
694 *              LATPOLEa, and also RADESYSa and EQUINOXa which provide
695 *              defaults for each other.  Thus one potential difficulty in
696 *              using WCSHDR_AUXIMG is that of erroneously inheriting one of
697 *              these four keywords.
698 *
699 *              Also, beware of potential inconsistencies that may arise where,
700 *              for example, DATE-OBS is inherited, but MJD-OBS is overridden
701 *              by MJDOBn and specifies a different time.  Pairs in this
702 *              category are:
703 *
704 =                    DATE-OBS/DOBSn       versus       MJD-OBS/MJDOBn
705 =                    DATE-AVG/DAVGn       versus       MJD-AVG/MJDAn
706 =                    RESTFRQa/RFRQna      versus      RESTWAVa/RWAVna
707 =                OBSGEO-[XYZ]/OBSG[XYZ]n  versus  OBSGEO-[LBH]/OBSG[LBH]n
708 *
709 *              The wcsfixi() routines datfix() and obsfix() are provided to
710 *              check the consistency of these and other such pairs of
711 *              keywords.
712 *
713 *              Unlike WCSHDR_ALLIMG, the existence of one (or all) of these
714 *              auxiliary WCS image header keywords will not by itself cause a
715 *              wcsprm struct to be created for alternate representation "a".
716 *              This is because they do not provide sufficient information to
717 *              create a non-trivial coordinate representation when used in
718 *              conjunction with the default values of those keywords that are
719 *              parameterized by axis number, such as CTYPEia.
720 *
721 *      - WCSHDR_ALLIMG (wcsbth() only): Allow the image-header form of *all*
722 *              image header WCS keywords to provide a default value for all
723 *              image arrays in a binary table (n.b. not pixel list).  This
724 *              default may be overridden by the column-specific form of the
725 *              keyword.
726 *
727 *              For example, a keyword like CRPIXja would apply to all image
728 *              arrays in a binary table with alternate representation "a"
729 *              unless overridden by jCRPna.
730 *
731 *              Specifically the keywords are those listed above for
732 *              WCSHDR_AUXIMG plus
733 *
734 #                WCSAXESa  for WCAXna
735 *
736 *              which defines the coordinate dimensionality, and the following
737 *              keywords that are parameterized by axis number:
738 *
739 #                CRPIXja   for jCRPna
740 #                PCi_ja    for ijPCna
741 #                CDi_ja    for ijCDna
742 #                CDELTia   for iCDEna
743 #                CROTAi    for iCROTn
744 #                CROTAia        -      ... Only if WCSHDR_CROTAia is set.
745 #                CUNITia   for iCUNna
746 #                CTYPEia   for iCTYna
747 #                CRVALia   for iCRVna
748 #                PVi_ma    for iVn_ma
749 #                PSi_ma    for iSn_ma
750 #
751 #                CNAMEia   for iCNAna
752 #                CRDERia   for iCRDna
753 #                CSYERia   for iCSYna
754 #                CZPHSia   for iCZPna
755 #                CPERIia   for iCPRna
756 *
757 *              where the image-header keywords on the left provide default
758 *              values for the column specific keywords on the right.
759 *
760 *              This full inheritance mechanism only applies to binary table
761 *              image arrays, not pixel lists, because in the latter case
762 *              there is no well-defined association between coordinate axis
763 *              number and column number (see note 9 below).
764 *
765 *              Note that CNAMEia, CRDERia, CSYERia, and their variants are
766 *              not used by WCSLIB but are stored in the wcsprm struct as
767 *              auxiliary information.
768 *
769 *              Note especially that at least one wcsprm struct will be
770 *              returned for each "a" found in one of the image header
771 *              keywords listed above:
772 *
773 *              - If the image header keywords for "a" ARE NOT inherited by a
774 *                binary table, then the struct will not be associated with
775 *                any particular table column number and it is up to the user
776 *                to provide an association.
777 *
778 *              - If the image header keywords for "a" ARE inherited by a
779 *                binary table image array, then those keywords are considered
780 *                to be "exhausted" and do not result in a separate wcsprm
781 *                struct.
782 *
783 *      For example, to accept CD00i00j and PC00i00j and reject all other
784 *      extensions, use
785 *
786 =        relax = WCSHDR_reject | WCSHDR_CD00i00j | WCSHDR_PC00i00j;
787 *
788 *      The parser always treats EPOCH as subordinate to EQUINOXa if both are
789 *      present, and VSOURCEa is always subordinate to ZSOURCEa.
790 *
791 *      Likewise, VELREF is subordinate to the formalism of WCS Paper III, see
792 *      spcaips().
793 *
794 *      Neither wcspih() nor wcsbth() currently recognize the AIPS-convention
795 *      keywords ALTRPIX or ALTRVAL which effectively define an alternative
796 *      representation for a spectral axis.
797 *
798 *   6: Depending on what flags have been set in its "relax" argument,
799 *      wcsbth() could return as many as 27027 wcsprm structs:
800 *
801 *      - Up to 27 unattached representations derived from image header
802 *        keywords.
803 *
804 *      - Up to 27 structs for each of up to 999 columns containing an image
805 *        arrays.
806 *
807 *      - Up to 27 structs for a pixel list.
808 *
809 *      Note that it is considered legitimate for a column to contain an image
810 *      array and also form part of a pixel list, and in particular that
811 *      wcsbth() does not check the TFORM keyword for a pixel list column to
812 *      check that it is scalar.
813 *
814 *      In practice, of course, a realistic binary table header is unlikely to
815 *      contain more than a handful of images.
816 *
817 *      In order for wcsbth() to create a wcsprm struct for a particular
818 *      coordinate representation, at least one WCS keyword that defines an
819 *      axis number must be present, either directly or by inheritance if
820 *      WCSHDR_ALLIMG is set.
821 *
822 *      When the image header keywords for an alternate representation are
823 *      inherited by a binary table image array via WCSHDR_ALLIMG, those
824 *      keywords are considered to be "exhausted" and do not result in a
825 *      separate wcsprm struct.  Otherwise they do.
826 *
827 *   7: Neither wcspih() nor wcsbth() check for duplicated keywords, in most
828 *      cases they accept the last encountered.
829 *
830 *   8: wcspih() and wcsbth() use wcsnpv() and wcsnps() (refer to the prologue
831 *      of wcs.h) to match the size of the pv[] and ps[] arrays in the wcsprm
832 *      structs to the number in the header.  Consequently there are no unused
833 *      elements in the pv[] and ps[] arrays, indeed they will often be of
834 *      zero length.
835 *
836 *   9: The FITS WCS standard for pixel lists assumes that a pixel list
837 *      defines one and only one image, i.e. that each row of the binary table
838 *      refers to just one event, e.g. the detection of a single photon or
839 *      neutrino, for which the device "pixel" coordinates are stored in
840 *      separate scalar columns of the table.
841 *
842 *      In the absence of a standard for pixel lists - or even an informal
843 *      description! - let alone a formal mechanism for identifying the columns
844 *      containing pixel coordinates (as opposed to pixel values or metadata
845 *      recorded at the time the photon or neutrino was detected), WCS Paper I
846 *      discusses how the WCS keywords themselves may be used to identify them.
847 *
848 *      In practice, however, pixel lists have been used to store multiple
849 *      images.  Besides not specifying how to identify columns, the pixel list
850 *      convention is also silent on the method to be used to associate table
851 *      columns with image axes.
852 *
853 *      An additional shortcoming is the absence of a formal method for
854 *      associating global binary-table WCS keywords, such as WCSNna or MJDOBn,
855 *      with a pixel list image, whether one or several.
856 *
857 *      In light of these uncertainties, wcsbth() simply collects all WCS
858 *      keywords for a particular pixel list coordinate representation (i.e.
859 *      the "a" value in TCTYna) into one wcsprm struct.  However, these
860 *      alternates need not be associated with the same table columns and this
861 *      allows a pixel list to contain up to 27 separate images.  As usual, if
862 *      one of these representations happened to contain more than two
863 *      celestial axes, for example, then an error would result when wcsset()
864 *      is invoked on it.  In this case the "colsel" argument could be used to
865 *      restrict the columns used to construct the representation so that it
866 *      only contained one pair of celestial axes.
867 *
868 *      Global, binary-table WCS keywords are considered to apply to the pixel
869 *      list image with matching alternate (e.g. the "a" value in LONPna or
870 *      EQUIna), regardless of the table columns the image occupies.  In other
871 *      words, the column number is ignored (the "n" value in LONPna or
872 *      EQUIna).  This also applies for global, binary-table WCS keywords that
873 *      have no alternates, such as MJDOBn and OBSGXn, which match all images
874 *      in a pixel list.  Take heed that this may lead to counterintuitive
875 *      behaviour, especially where such a keyword references a column that
876 *      does not store pixel coordinates, and moreso where the pixel list
877 *      stores only a single image.  In fact, as the column number, n, is
878 *      ignored for such keywords, it would make no difference even if they
879 *      referenced non-existent columns.  Moreover, there is no requirement for
880 *      consistency in the column numbers used for such keywords, even for
881 *      OBSGXn, OBSGYn, and OBSGZn which are meant to define the elements of a
882 *      coordinate vector.  Although it would surely be perverse to construct a
883 *      pixel list like this, such a situation may still arise in practice
884 *      where columns are deleted from a binary table.
885 *
886 *      The situation with global, binary-table WCS keywords becomes
887 *      potentially even more confusing when image arrays and pixel list images
888 *      coexist in one binary table.  In that case, a keyword such as MJDOBn
889 *      may legitimately appear multiple times with n referencing different
890 *      image arrays.  Which then is the one that applies to the pixel list
891 *      images?  In this implementation, it is the last instance that appears
892 *      in the header, whether or not it is also associated with an image
893 *      array.
894 *
895 *
896 * wcstab() - Tabular construction routine
897 * ---------------------------------------
898 * wcstab() assists in filling in the information in the wcsprm struct relating
899 * to coordinate lookup tables.
900 *
901 * Tabular coordinates ('TAB') present certain difficulties in that the main
902 * components of the lookup table - the multidimensional coordinate array plus
903 * an index vector for each dimension - are stored in a FITS binary table
904 * extension (BINTABLE).  Information required to locate these arrays is stored
905 * in PVi_ma and PSi_ma keywords in the image header.
906 *
907 * wcstab() parses the PVi_ma and PSi_ma keywords associated with each 'TAB'
908 * axis and allocates memory in the wcsprm struct for the required number of
909 * tabprm structs.  It sets as much of the tabprm struct as can be gleaned from
910 * the image header, and also sets up an array of wtbarr structs (described in
911 * the prologue of wtbarr.h) to assist in extracting the required arrays from
912 * the BINTABLE extension(s).
913 *
914 * It is then up to the user to allocate memory for, and copy arrays from the
915 * BINTABLE extension(s) into the tabprm structs.  A CFITSIO routine,
916 * fits_read_wcstab(), has been provided for this purpose, see getwcstab.h.
917 * wcsset() will automatically take control of this allocated memory, in
918 * particular causing it to be freed by wcsfree(); the user must not attempt
919 * to free it after wcsset() has been called.
920 *
921 * Note that wcspih() and wcsbth() automatically invoke wcstab() on each of the
922 * wcsprm structs that they return.
923 *
924 * Given and returned:
925 *   wcs       struct wcsprm*
926 *                       Coordinate transformation parameters (see below).
927 *
928 *                       wcstab() sets ntab, tab, nwtb and wtb, allocating
929 *                       memory for the tab and wtb arrays.  This allocated
930 *                       memory will be freed automatically by wcsfree().
931 *
932 * Function return value:
933 *             int       Status return value:
934 *                         0: Success.
935 *                         1: Null wcsprm pointer passed.
936 *                         2: Memory allocation failed.
937 *                         3: Invalid tabular parameters.
938 *
939 *                       For returns > 1, a detailed error message is set in
940 *                       wcsprm::err if enabled, see wcserr_enable().
941 *
942 *
943 * wcsidx() - Index alternate coordinate representations
944 * -----------------------------------------------------
945 * wcsidx() returns an array of 27 indices for the alternate coordinate
946 * representations in the array of wcsprm structs returned by wcspih().  For
947 * the array returned by wcsbth() it returns indices for the unattached
948 * (colnum == 0) representations derived from image header keywords - use
949 * wcsbdx() for those derived from binary table image arrays or pixel lists
950 * keywords.
951 *
952 * Given:
953 *   nwcs      int       Number of coordinate representations in the array.
954 *
955 *   wcs       const struct wcsprm**
956 *                       Pointer to an array of wcsprm structs returned by
957 *                       wcspih() or wcsbth().
958 *
959 * Returned:
960 *   alts      int[27]   Index of each alternate coordinate representation in
961 *                       the array: alts[0] for the primary, alts[1] for 'A',
962 *                       etc., set to -1 if not present.
963 *
964 *                       For example, if there was no 'P' representation then
965 *
966 =                         alts['P'-'A'+1] == -1;
967 *
968 *                       Otherwise, the address of its wcsprm struct would be
969 *
970 =                         wcs + alts['P'-'A'+1];
971 *
972 * Function return value:
973 *             int       Status return value:
974 *                         0: Success.
975 *                         1: Null wcsprm pointer passed.
976 *
977 *
978 * wcsbdx() - Index alternate coordinate representions
979 * ---------------------------------------------------
980 * wcsbdx() returns an array of 999 x 27 indices for the alternate coordinate
981 * representions for binary table image arrays xor pixel lists in the array of
982 * wcsprm structs returned by wcsbth().  Use wcsidx() for the unattached
983 * representations derived from image header keywords.
984 *
985 * Given:
986 *   nwcs      int       Number of coordinate representations in the array.
987 *
988 *   wcs       const struct wcsprm**
989 *                       Pointer to an array of wcsprm structs returned by
990 *                       wcsbth().
991 *
992 *   type      int       Select the type of coordinate representation:
993 *                         0: binary table image arrays,
994 *                         1: pixel lists.
995 *
996 * Returned:
997 *   alts      short[1000][28]
998 *                       Index of each alternate coordinate represention in the
999 *                       array: alts[col][0] for the primary, alts[col][1] for
1000 *                       'A', to alts[col][26] for 'Z', where col is the
1001 *                       1-relative column number, and col == 0 is used for
1002 *                       unattached image headers.  Set to -1 if not present.
1003 *
1004 *                       alts[col][27] counts the number of coordinate
1005 *                       representations of the chosen type for each column.
1006 *
1007 *                       For example, if there was no 'P' represention for
1008 *                       column 13 then
1009 *
1010 =                         alts[13]['P'-'A'+1] == -1;
1011 *
1012 *                       Otherwise, the address of its wcsprm struct would be
1013 *
1014 =                         wcs + alts[13]['P'-'A'+1];
1015 *
1016 * Function return value:
1017 *             int       Status return value:
1018 *                         0: Success.
1019 *                         1: Null wcsprm pointer passed.
1020 *
1021 *
1022 * wcsvfree() - Free the array of wcsprm structs
1023 * ---------------------------------------------
1024 * wcsvfree() frees the memory allocated by wcspih() or wcsbth() for the array
1025 * of wcsprm structs, first invoking wcsfree() on each of the array members.
1026 *
1027 * Given and returned:
1028 *   nwcs      int*      Number of coordinate representations found; set to 0
1029 *                       on return.
1030 *
1031 *   wcs       struct wcsprm**
1032 *                       Pointer to the array of wcsprm structs; set to 0x0 on
1033 *                       return.
1034 *
1035 * Function return value:
1036 *             int       Status return value:
1037 *                         0: Success.
1038 *                         1: Null wcsprm pointer passed.
1039 *
1040 *
1041 * wcshdo() - Write out a wcsprm struct as a FITS header
1042 * -----------------------------------------------------
1043 * wcshdo() translates a wcsprm struct into a FITS header.  If the colnum
1044 * member of the struct is non-zero then a binary table image array header will
1045 * be produced.  Otherwise, if the colax[] member of the struct is set non-zero
1046 * then a pixel list header will be produced.  Otherwise, a primary image or
1047 * image extension header will be produced.
1048 *
1049 * If the struct was originally constructed from a header, e.g. by wcspih(),
1050 * the output header will almost certainly differ in a number of respects:
1051 *
1052 *   - The output header only contains WCS-related keywords.  In particular, it
1053 *     does not contain syntactically-required keywords such as SIMPLE, NAXIS,
1054 *     BITPIX, or END.
1055 *
1056 *   - Elements of the PCi_ja matrix will be written if and only if they differ
1057 *     from the unit matrix.  Thus, if the matrix is unity then no elements
1058 *     will be written.
1059 *
1060 *   - The redundant keywords MJDREF, JDREF, JDREFI, JDREFF, all of which
1061 *     duplicate MJDREFI + MJDREFF, are never written.  OBSGEO-[LBH] are not
1062 *     written if OBSGEO-[XYZ] are defined.
1063 *
1064 *   - Deprecated (e.g. CROTAn, RESTFREQ, VELREF, RADECSYS, EPOCH, VSOURCEa) or
1065 *     non-standard usage will be translated to standard (this is partially
1066 *     dependent on whether wcsfix() was applied).
1067 *
1068 *   - Additional keywords such as WCSAXESa, CUNITia, LONPOLEa and LATPOLEa may
1069 *     appear.
1070 *
1071 *   - Quantities will be converted to the units used internally, basically SI
1072 *     with the addition of degrees.
1073 *
1074 *   - Floating-point quantities may be given to a different decimal precision.
1075 *
1076 *   - The original keycomments will be lost, although wcshdo() tries hard to
1077 *     write meaningful comments.
1078 *
1079 *   - Keyword order will almost certainly be changed.
1080 *
1081 * Keywords can be translated between the image array, binary table, and pixel
1082 * lists forms by manipulating the colnum or colax[] members of the wcsprm
1083 * struct.
1084 *
1085 * Given:
1086 *   ctrl      int       Vector of flag bits that controls the degree of
1087 *                       permissiveness in departing from the published WCS
1088 *                       standard, and also controls the formatting of
1089 *                       floating-point keyvalues.  Set it to zero to get the
1090 *                       default behaviour.
1091 *
1092 *                       Flag bits for the degree of permissiveness:
1093 *                         WCSHDO_none: Recognize only FITS keywords defined by
1094 *                            the published WCS standard.
1095 *                         WCSHDO_all: Admit all recognized informal extensions
1096 *                            of the WCS standard.
1097 *                       Fine-grained control of the degree of permissiveness
1098 *                       is also possible as explained in the notes below.
1099 *
1100 *                       As for controlling floating-point formatting, by
1101 *                       default wcshdo() uses "%20.12G" for non-parameterized
1102 *                       keywords such as LONPOLEa, and attempts to make the
1103 *                       header more human-readable by using the same "%f"
1104 *                       format for all values of each of the following
1105 *                       parameterized keywords: CRPIXja, PCi_ja, and CDELTia
1106 *                       (n.b. excluding CRVALia).  Each has the same field
1107 *                       width and precision so that the decimal points line
1108 *                       up.  The precision, allowing for up to 15 significant
1109 *                       digits, is chosen so that there are no excess trailing
1110 *                       zeroes.  A similar formatting scheme applies by
1111 *                       default for distortion function parameters.
1112 *
1113 *                       However, where the values of, for example, CDELTia
1114 *                       differ by many orders of magnitude, the default
1115 *                       formatting scheme may cause unacceptable loss of
1116 *                       precision for the lower-valued keyvalues.  Thus the
1117 *                       default behaviour may be overridden:
1118 *                         WCSHDO_P12: Use "%20.12G" format for all floating-
1119 *                            point keyvalues (12 significant digits).
1120 *                         WCSHDO_P13: Use "%21.13G" format for all floating-
1121 *                            point keyvalues (13 significant digits).
1122 *                         WCSHDO_P14: Use "%22.14G" format for all floating-
1123 *                            point keyvalues (14 significant digits).
1124 *                         WCSHDO_P15: Use "%23.15G" format for all floating-
1125 *                            point keyvalues (15 significant digits).
1126 *                         WCSHDO_P16: Use "%24.16G" format for all floating-
1127 *                            point keyvalues (16 significant digits).
1128 *                         WCSHDO_P17: Use "%25.17G" format for all floating-
1129 *                            point keyvalues (17 significant digits).
1130 *                       If more than one of the above flags are set, the
1131 *                       highest number of significant digits prevails.  In
1132 *                       addition, there is an anciliary flag:
1133 *                         WCSHDO_EFMT: Use "%E" format instead of the default
1134 *                            "%G" format above.
1135 *                       Note that excess trailing zeroes are stripped off the
1136 *                       fractional part with "%G" (which never occurs with
1137 *                       "%E").  Note also that the higher-precision options
1138 *                       eat into the keycomment area.  In this regard,
1139 *                       WCSHDO_P14 causes minimal disruption with "%G" format,
1140 *                       while WCSHDO_P13 is appropriate with "%E".
1141 *
1142 * Given and returned:
1143 *   wcs       struct wcsprm*
1144 *                       Pointer to a wcsprm struct containing coordinate
1145 *                       transformation parameters.  Will be initialized if
1146 *                       necessary.
1147 *
1148 * Returned:
1149 *   nkeyrec   int*      Number of FITS header keyrecords returned in the
1150 *                       "header" array.
1151 *
1152 *   header    char**    Pointer to an array of char holding the header.
1153 *                       Storage for the array is allocated by wcshdo() in
1154 *                       blocks of 2880 bytes (32 x 80-character keyrecords)
1155 *                       and must be freed by the user to avoid memory leaks.
1156 *                       See wcsdealloc().
1157 *
1158 *                       Each keyrecord is 80 characters long and is *NOT*
1159 *                       null-terminated, so the first keyrecord starts at
1160 *                       (*header)[0], the second at (*header)[80], etc.
1161 *
1162 * Function return value:
1163 *             int       Status return value (associated with wcs_errmsg[]):
1164 *                         0: Success.
1165 *                         1: Null wcsprm pointer passed.
1166 *                         2: Memory allocation failed.
1167 *                         3: Linear transformation matrix is singular.
1168 *                         4: Inconsistent or unrecognized coordinate axis
1169 *                            types.
1170 *                         5: Invalid parameter value.
1171 *                         6: Invalid coordinate transformation parameters.
1172 *                         7: Ill-conditioned coordinate transformation
1173 *                            parameters.
1174 *
1175 *                       For returns > 1, a detailed error message is set in
1176 *                       wcsprm::err if enabled, see wcserr_enable().
1177 *
1178 * Notes:
1179 *   wcshdo() interprets the "relax" argument as a vector of flag bits to
1180 *   provide fine-grained control over what non-standard WCS keywords to write.
1181 *   The flag bits are subject to change in future and should be set by using
1182 *   the preprocessor macros (see below) for the purpose.
1183 *
1184 *   - WCSHDO_none: Don't use any extensions.
1185 *
1186 *   - WCSHDO_all: Write all recognized extensions, equivalent to setting each
1187 *           flag bit.
1188 *
1189 *   - WCSHDO_safe: Write all extensions that are considered to be safe and
1190 *           recommended.
1191 *
1192 *   - WCSHDO_DOBSn: Write DOBSn, the column-specific analogue of DATE-OBS for
1193 *           use in binary tables and pixel lists.  WCS Paper III introduced
1194 *           DATE-AVG and DAVGn but by an oversight DOBSn (the obvious analogy)
1195 *           was never formally defined by the standard.  The alternative to
1196 *           using DOBSn is to write DATE-OBS which applies to the whole table.
1197 *           This usage is considered to be safe and is recommended.
1198 *
1199 *   - WCSHDO_TPCn_ka: WCS Paper I defined
1200 *
1201 *           - TPn_ka and TCn_ka for pixel lists
1202 *
1203 *           but WCS Paper II uses TPCn_ka in one example and subsequently the
1204 *           errata for the WCS papers legitimized the use of
1205 *
1206 *           - TPCn_ka and TCDn_ka for pixel lists
1207 *
1208 *           provided that the keyword does not exceed eight characters.  This
1209 *           usage is considered to be safe and is recommended because of the
1210 *           non-mnemonic terseness of the shorter forms.
1211 *
1212 *   - WCSHDO_PVn_ma: WCS Paper I defined
1213 *
1214 *           - iVn_ma and iSn_ma for bintables and
1215 *           - TVn_ma and TSn_ma for pixel lists
1216 *
1217 *           but WCS Paper II uses iPVn_ma and TPVn_ma in the examples and
1218 *           subsequently the errata for the WCS papers legitimized the use of
1219 *
1220 *           - iPVn_ma and iPSn_ma for bintables and
1221 *           - TPVn_ma and TPSn_ma for pixel lists
1222 *
1223 *           provided that the keyword does not exceed eight characters.  This
1224 *           usage is considered to be safe and is recommended because of the
1225 *           non-mnemonic terseness of the shorter forms.
1226 *
1227 *   - WCSHDO_CRPXna: For historical reasons WCS Paper I defined
1228 *
1229 *           - jCRPXn, iCDLTn, iCUNIn, iCTYPn, and iCRVLn for bintables and
1230 *           - TCRPXn, TCDLTn, TCUNIn, TCTYPn, and TCRVLn for pixel lists
1231 *
1232 *           for use without an alternate version specifier.  However, because
1233 *           of the eight-character keyword constraint, in order to accommodate
1234 *           column numbers greater than 99 WCS Paper I also defined
1235 *
1236 *           - jCRPna, iCDEna, iCUNna, iCTYna and iCRVna for bintables and
1237 *           - TCRPna, TCDEna, TCUNna, TCTYna and TCRVna for pixel lists
1238 *
1239 *           for use with an alternate version specifier (the "a").  Like the
1240 *           PC, CD, PV, and PS keywords there is an obvious tendency to
1241 *           confuse these two forms for column numbers up to 99.  It is very
1242 *           unlikely that any parser would reject keywords in the first set
1243 *           with a non-blank alternate version specifier so this usage is
1244 *           considered to be safe and is recommended.
1245 *
1246 *   - WCSHDO_CNAMna: WCS Papers I and III defined
1247 *
1248 *           - iCNAna,  iCRDna,  and iCSYna  for bintables and
1249 *           - TCNAna,  TCRDna,  and TCSYna  for pixel lists
1250 *
1251 *           By analogy with the above, the long forms would be
1252 *
1253 *           - iCNAMna, iCRDEna, and iCSYEna for bintables and
1254 *           - TCNAMna, TCRDEna, and TCSYEna for pixel lists
1255 *
1256 *           Note that these keywords provide auxiliary information only, none
1257 *           of them are needed to compute world coordinates.  This usage is
1258 *           potentially unsafe and is not recommended at this time.
1259 *
1260 *   - WCSHDO_WCSNna: In light of wcsbth() note 4, write WCSNna instead of
1261 *           TWCSna for pixel lists.  While wcsbth() treats WCSNna and TWCSna
1262 *           as equivalent, other parsers may not.  Consequently, this usage
1263 *           is potentially unsafe and is not recommended at this time.
1264 *
1265 *
1266 * Global variable: const char *wcshdr_errmsg[] - Status return messages
1267 * ---------------------------------------------------------------------
1268 * Error messages to match the status value returned from each function.
1269 * Use wcs_errmsg[] for status returns from wcshdo().
1270 *
1271 *===========================================================================*/
1272 
1273 #ifndef WCSLIB_WCSHDR
1274 #define WCSLIB_WCSHDR
1275 
1276 #include "wcs.h"
1277 
1278 #ifdef __cplusplus
1279 extern "C" {
1280 #endif
1281 
1282 #define WCSHDR_none     0x00000000
1283 #define WCSHDR_all      0x000FFFFF
1284 #define WCSHDR_reject   0x10000000
1285 #define WCSHDR_strict   0x20000000
1286 
1287 #define WCSHDR_CROTAia  0x00000001
1288 #define WCSHDR_VELREFa  0x00000002
1289 #define WCSHDR_CD00i00j 0x00000004
1290 #define WCSHDR_PC00i00j 0x00000008
1291 #define WCSHDR_PROJPn   0x00000010
1292 #define WCSHDR_CD0i_0ja 0x00000020
1293 #define WCSHDR_PC0i_0ja 0x00000040
1294 #define WCSHDR_PV0i_0ma 0x00000080
1295 #define WCSHDR_PS0i_0ma 0x00000100
1296 #define WCSHDR_DOBSn    0x00000200
1297 #define WCSHDR_OBSGLBHn 0x00000400
1298 #define WCSHDR_RADECSYS 0x00000800
1299 #define WCSHDR_EPOCHa   0x00001000
1300 #define WCSHDR_VSOURCE  0x00002000
1301 #define WCSHDR_DATEREF  0x00004000
1302 #define WCSHDR_LONGKEY  0x00008000
1303 #define WCSHDR_CNAMn    0x00010000
1304 #define WCSHDR_AUXIMG   0x00020000
1305 #define WCSHDR_ALLIMG   0x00040000
1306 
1307 #define WCSHDR_IMGHEAD  0x00100000
1308 #define WCSHDR_BIMGARR  0x00200000
1309 #define WCSHDR_PIXLIST  0x00400000
1310 
1311 #define WCSHDO_none     0x00000
1312 #define WCSHDO_all      0x000FF
1313 #define WCSHDO_safe     0x0000F
1314 #define WCSHDO_DOBSn    0x00001
1315 #define WCSHDO_TPCn_ka  0x00002
1316 #define WCSHDO_PVn_ma   0x00004
1317 #define WCSHDO_CRPXna   0x00008
1318 #define WCSHDO_CNAMna   0x00010
1319 #define WCSHDO_WCSNna   0x00020
1320 #define WCSHDO_P12      0x01000
1321 #define WCSHDO_P13      0x02000
1322 #define WCSHDO_P14      0x04000
1323 #define WCSHDO_P15      0x08000
1324 #define WCSHDO_P16      0x10000
1325 #define WCSHDO_P17      0x20000
1326 #define WCSHDO_EFMT     0x40000
1327 
1328 
1329 extern const char *wcshdr_errmsg[];
1330 
1331 enum wcshdr_errmsg_enum {
1332   WCSHDRERR_SUCCESS            = 0,	// Success.
1333   WCSHDRERR_NULL_POINTER       = 1,	// Null wcsprm pointer passed.
1334   WCSHDRERR_MEMORY             = 2,	// Memory allocation failed.
1335   WCSHDRERR_BAD_COLUMN         = 3,	// Invalid column selection.
1336   WCSHDRERR_PARSER             = 4,	// Fatal error returned by Flex
1337 					// parser.
1338   WCSHDRERR_BAD_TABULAR_PARAMS = 5 	// Invalid tabular parameters.
1339 };
1340 
1341 int wcspih(char *header, int nkeyrec, int relax, int ctrl, int *nreject,
1342            int *nwcs, struct wcsprm **wcs);
1343 
1344 int wcsbth(char *header, int nkeyrec, int relax, int ctrl, int keysel,
1345            int *colsel, int *nreject, int *nwcs, struct wcsprm **wcs);
1346 
1347 int wcstab(struct wcsprm *wcs);
1348 
1349 int wcsidx(int nwcs, struct wcsprm **wcs, int alts[27]);
1350 
1351 int wcsbdx(int nwcs, struct wcsprm **wcs, int type, short alts[1000][28]);
1352 
1353 int wcsvfree(int *nwcs, struct wcsprm **wcs);
1354 
1355 int wcshdo(int ctrl, struct wcsprm *wcs, int *nkeyrec, char **header);
1356 
1357 
1358 #ifdef __cplusplus
1359 }
1360 #endif
1361 
1362 #endif // WCSLIB_WCSHDR
1363