1 package nom.tam.fits;
2
3 import java.io.EOFException;
4 import java.io.IOException;
5 import java.io.PrintStream;
6 import java.math.BigDecimal;
7 import java.math.BigInteger;
8 import java.util.ArrayList;
9 import java.util.Arrays;
10 import java.util.Comparator;
11 import java.util.HashSet;
12 import java.util.List;
13 import java.util.Set;
14 import java.util.logging.Level;
15 import java.util.logging.Logger;
16
17 import nom.tam.fits.FitsFactory.FitsSettings;
18 import nom.tam.fits.header.Bitpix;
19 import nom.tam.fits.header.Checksum;
20 import nom.tam.fits.header.IFitsHeader;
21 import nom.tam.fits.header.IFitsHeader.VALUE;
22 import nom.tam.fits.header.Standard;
23 import nom.tam.fits.utilities.FitsCheckSum;
24 import nom.tam.util.ArrayDataInput;
25 import nom.tam.util.ArrayDataOutput;
26 import nom.tam.util.AsciiFuncs;
27 import nom.tam.util.ComplexValue;
28 import nom.tam.util.Cursor;
29 import nom.tam.util.FitsIO;
30 import nom.tam.util.FitsInputStream;
31 import nom.tam.util.FitsOutput;
32 import nom.tam.util.HashedList;
33 import nom.tam.util.RandomAccess;
34
35 /*
36 * #%L
37 * nom.tam FITS library
38 * %%
39 * Copyright (C) 2004 - 2024 nom-tam-fits
40 * %%
41 * This is free and unencumbered software released into the public domain.
42 *
43 * Anyone is free to copy, modify, publish, use, compile, sell, or
44 * distribute this software, either in source code form or as a compiled
45 * binary, for any purpose, commercial or non-commercial, and by any
46 * means.
47 *
48 * In jurisdictions that recognize copyright laws, the author or authors
49 * of this software dedicate any and all copyright interest in the
50 * software to the public domain. We make this dedication for the benefit
51 * of the public at large and to the detriment of our heirs and
52 * successors. We intend this dedication to be an overt act of
53 * relinquishment in perpetuity of all present and future rights to this
54 * software under copyright law.
55 *
56 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
57 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
58 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
59 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
60 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
61 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
62 * OTHER DEALINGS IN THE SOFTWARE.
63 * #L%
64 */
65
66 import static nom.tam.fits.header.Standard.BITPIX;
67 import static nom.tam.fits.header.Standard.BLANKS;
68 import static nom.tam.fits.header.Standard.COMMENT;
69 import static nom.tam.fits.header.Standard.END;
70 import static nom.tam.fits.header.Standard.EXTEND;
71 import static nom.tam.fits.header.Standard.GCOUNT;
72 import static nom.tam.fits.header.Standard.GROUPS;
73 import static nom.tam.fits.header.Standard.HISTORY;
74 import static nom.tam.fits.header.Standard.NAXIS;
75 import static nom.tam.fits.header.Standard.NAXISn;
76 import static nom.tam.fits.header.Standard.PCOUNT;
77 import static nom.tam.fits.header.Standard.SIMPLE;
78 import static nom.tam.fits.header.Standard.TFIELDS;
79 import static nom.tam.fits.header.Standard.XTENSION;
80 import static nom.tam.fits.header.Standard.XTENSION_BINTABLE;
81 import static nom.tam.fits.header.extra.CXCExt.LONGSTRN;
82
83 /**
84 * <p>
85 * Access and manipulate the header of a HDU. FITS headers serve more than a single purpose:
86 * </p>
87 * <ol>
88 * <li>provide an essential description of the type, size, and layout of the HDUs data segment</li>
89 * <li>describe the data as completely as possible via standardized (or conventional) keywords</li>
90 * <li>provide storage for additional user-specific key / value pairs</li>
91 * <li>allow for comments to aid human readability</li>
92 * </ol>
93 * <p>
94 * First and foremost headers provide a description of the data object that follows the header in the HDU. Some of that
95 * description is essential and critical to the integrity of the FITS file, such as the header keywords that describe
96 * the type, size, and layout of the data segment. This library will automatically populate the header with appropriate
97 * information using the mandatory keywords (such as <code>SIMPLE</code> or <code>XTENSION</code>, <code>BITPIX</code>,
98 * <code>NAXIS</code>, <code>NAXIS</code><i>n</i>, <code>PCOUNT</code>, <code>GCOUNT</code> keywords, as well as
99 * essential table column format descriptions). Users of the library should avoid overwriting these mandatory keywords
100 * manually, since they may corrupt the FITS file, rendering it unreadable.
101 * </p>
102 * <p>
103 * Beyond the keywords that describe the type, shape, and size of data, the library will not add further information to
104 * the header. The users of the library are responsible to complete the header description as necessary. This includes
105 * non-enssential data descriptions (such as <code>EXTNAME</code>, <code>BUNIT</code>, <code>OBSERVER</code>, or
106 * optional table column descriptors <code>TTYPE</code><i>n</i>, <code>TUNIT</code><i>n</i>, coordinate systems via the
107 * appropriate WCS keywords, or checksums). Users of the library are responsible for completing the data description
108 * using whatever standard or conventional keywords are available and appropriate. Please refer to the
109 * <a href="https://fits.gsfc.nasa.gov/fits_standard.html">FITS Standard</a> documentation to see what typical
110 * descriptions of data you might want to use.
111 * </p>
112 * <p>
113 * Last but not least, the header is also a place where FITS creators can store (nearly) arbitrary key/value pairs. In
114 * earlier versions of the FITS standard, header keywords were restricted to max. 8 upper case letters and numbers (plus
115 * hyphen and underscore), and no more than 70 character value fields. However, as of FITS 4.0 (and even before as a
116 * registered convention), string values of arbitrary length may be stored using the OGIP 1.0 long string convention,
117 * while the ESO <a href="https://fits.gsfc.nasa.gov/registry/hierarch_keyword.html">HIERARCH convention</a> allows
118 * keywords with more than 8 characters and hierarchical keywords. Support, conformance, and compliance to these
119 * conventions can be toggled by static settings in {@link FitsFactory} to user preference.
120 * </p>
121 * <p>
122 * As of version 1.16, we also support reserving space in headers for future additions using the
123 * {@link #ensureCardSpace(int)} method, also part of the FITS 4.0 standard. It allows users to finish populating
124 * headers <i>after</i> data that follows the header is already written -- a useful feature for recording data from
125 * streaming sources.
126 * </p>
127 */
128 @SuppressWarnings("deprecation")
129 public class Header implements FitsElement {
130
131 /**
132 * The default character position to which comments should be aligned if possible (zero-based). The fITS standard
133 * requires that 'fixed-format' values are right-justified to byte 30 (index 29 in Java), and recommends a space
134 * after that before the comment. As such, comments should normally start at byte 30 (counted from 0). (We will add
135 * a space at that position before the '/' indicating the comment start)
136 */
137 public static final int DEFAULT_COMMENT_ALIGN = 30;
138
139 /**
140 * The earliest position (zero-based) at which a comment may start for a regular key/value entry.
141 *
142 * @deprecated We will disable changing alignment in the future because it may violate the standard for
143 * 'fixed-format' header entries, and result in files that are unreadable by some other software.
144 * This constant will be obsoleted and removed.
145 */
146 @Deprecated
147 public static final int MIN_COMMENT_ALIGN = 20;
148
149 /**
150 * The largest (zero-based) comment alignment allowed that can still contain some meaningful comment (word)
151 *
152 * @deprecated We will disable changing alignment in the future because it may violate the standard for
153 * 'fixed-format' header entries, and result in files that are unreadable by some other software.
154 * This constant will be obsoleted and removed.
155 */
156 @Deprecated
157 public static final int MAX_COMMENT_ALIGN = 70;
158
159 /**
160 * The alignment position of card comments for a more pleasing visual experience. Comments will be aligned to this
161 * position, provided the lengths of all fields allow for it.
162 */
163 private static int commentAlign = DEFAULT_COMMENT_ALIGN;
164
165 private static final Logger LOG = Logger.getLogger(Header.class.getName());
166
167 private static final int MIN_NUMBER_OF_CARDS_FOR_VALID_HEADER = 4;
168
169 /**
170 * The actual header data stored as a HashedList of HeaderCard's.
171 */
172 private final HashedList<HeaderCard> cards;
173
174 /** Offset of this Header in the FITS file */
175 private long fileOffset;
176
177 private List<HeaderCard> duplicates;
178
179 private HashSet<String> dupKeys;
180
181 /** Input descriptor last time header was read */
182 private ArrayDataInput input;
183
184 /**
185 * The mimimum number of cards to write, including blank header space as described in the FITS 4.0 standard.
186 */
187 private int minCards;
188
189 /**
190 * The number of bytes that this header occupied in file. (for re-writing).
191 */
192 private long readSize;
193
194 /** The checksum calculated from the input stream */
195 private long streamSum = -1L;
196
197 /**
198 * the sorter used to sort the header cards defore writing the header.
199 */
200 private Comparator<String> headerSorter;
201
202 private BasicHDU<?> owner;
203
204 /**
205 * Keyword checking mode when adding standardized keywords via the {@link IFitsHeader} interface.
206 *
207 * @author Attila Kovacs
208 *
209 * @since 1.19
210 */
211 public enum KeywordCheck {
212 /** No keyword checking will be performed. */
213 NONE,
214 /** Check only that the keyword is appropriate for the type of data contained in the associated HDU */
215 DATA_TYPE,
216 /**
217 * Strict checking, will refuse to set mandatory FITS keywords -- which should normally be set by the library
218 * alone.
219 */
220 STRICT
221 }
222
223 /**
224 * The keyword checking mode used by the library until the user changes it it.
225 *
226 * @since 1.19
227 */
228 public static final KeywordCheck DEFAULT_KEYWORD_CHECK_POLICY = KeywordCheck.DATA_TYPE;
229
230 private static KeywordCheck defaultKeyCheck = DEFAULT_KEYWORD_CHECK_POLICY;
231
232 private KeywordCheck keyCheck = defaultKeyCheck;
233
234 /**
235 * Create a header by reading the information from the input stream.
236 *
237 * @param dis The input stream to read the data from.
238 *
239 * @return <CODE>null</CODE> if there was a problem with the header; otherwise return the
240 * header read from the input stream.
241 *
242 * @throws TruncatedFileException if the stream ended prematurely
243 * @throws IOException if the header could not be read.
244 */
245 public static Header readHeader(ArrayDataInput dis) throws TruncatedFileException, IOException {
246 Header myHeader = new Header();
247 try {
248 myHeader.read(dis);
249 } catch (EOFException e) {
250 // An EOF exception is thrown only if the EOF was detected
251 // when reading the first card. In this case we want
252 // to return a null.
253 return null;
254 }
255 return myHeader;
256 }
257
258 /**
259 * please use {@link FitsFactory#setLongStringsEnabled(boolean)} instead.
260 *
261 * @param flag the new value for long-string enabling.
262 */
263 @Deprecated
264 public static void setLongStringsEnabled(boolean flag) {
265 FitsFactory.setLongStringsEnabled(flag);
266 }
267
268 /** Create a new header with the required default keywords for a standalone header. */
269 public Header() {
270 cards = new HashedList<>();
271 headerSorter = new HeaderOrder();
272 duplicates = null;
273 clear();
274 }
275
276 /**
277 * Create a header and populate it from the input stream
278 *
279 * @param is The input stream where header information is expected.
280 *
281 * @throws IOException if the header could not be read.
282 * @throws TruncatedFileException if the stream ended prematurely
283 */
284 public Header(ArrayDataInput is) throws TruncatedFileException, IOException {
285 this();
286 read(is);
287 }
288
289 /**
290 * Create a header which points to the given data object.
291 *
292 * @param o The data object to be described.
293 *
294 * @throws FitsException if the data was not valid for this header.
295 */
296 public Header(Data o) throws FitsException {
297 this();
298 o.fillHeader(this);
299 }
300
301 /**
302 * Create a header and initialize it with a vector of strings.
303 *
304 * @param newCards Card images to be placed in the header.
305 */
306 public Header(String[] newCards) {
307 this();
308 for (String newCard : newCards) {
309 cards.add(HeaderCard.create(newCard));
310 }
311 }
312
313 void assignTo(BasicHDU<?> hdu) {
314 // if (owner != null) {
315 // throw new IllegalStateException("This header was already assigned to a HDU");
316 // }
317 this.owner = hdu;
318 }
319
320 /**
321 * Returns a copy of this header that is not attached to a HDU. The cards of the header, including duplicates are
322 * preserved.
323 *
324 * @return A new header that contains an independent copy of this header's content. The returned header will not be
325 * associated to any input or HDU, and will not share any mutable references with the original.
326 *
327 * @see #mergeDistinct(Header)
328 *
329 * @since 1.23
330 */
331 @SuppressWarnings("unchecked")
332 public Header getDetachedCopy() {
333 Header detached = new Header();
334
335 detached.minCards = minCards;
336 detached.headerSorter = headerSorter;
337 detached.keyCheck = keyCheck;
338
339 Cursor<String, HeaderCard> iterator = iterator();
340 while (iterator.hasNext()) {
341 detached.addLine(iterator.next().copy());
342 }
343
344 if (duplicates != null) {
345 detached.duplicates = new ArrayList<>(duplicates.size());
346 for (HeaderCard dup : duplicates) {
347 detached.duplicates.add(dup.copy());
348 }
349 }
350
351 if (dupKeys != null) {
352 detached.dupKeys = (HashSet<String>) dupKeys.clone();
353 }
354
355 return detached;
356 }
357
358 /**
359 * <p>
360 * Reserves header card space for populating at a later time. When written to a stream, the header will be large
361 * enough to hold at least the specified number of cards. If the header has fewer physical cards then the remaining
362 * space will be padded with blanks, leaving space for future additions, as specified by the FITS 4.0 standard for
363 * <a href="https://fits.gsfc.nasa.gov/registry/headerspace.html"> preallocated header space</a>.
364 * </p>
365 * <p>
366 * This method is also called by {@link #read(ArrayDataInput)}, with the number of cards (including reserved blank
367 * space) contained in the header input stream, in order to ensure that the header remains rewritable even if it is
368 * shortened by the removal of cards (explicitly, or because they were duplicates).
369 * </p>
370 * <p>
371 * A new setting always overrides prior ones. For example, calling this method with an argument that is %lt;=1 will
372 * eliminate (reset) any prior preallocated header space.
373 * </p>
374 *
375 * @param nCards the mimimum number of 80-character header records that is header must be able to support when
376 * written to a stream, including preallocated blank header space.
377 *
378 * @since 1.16
379 *
380 * @see #getMinimumSize()
381 * @see #write(ArrayDataOutput)
382 * @see #read(ArrayDataInput)
383 * @see #resetOriginalSize()
384 */
385 public void ensureCardSpace(int nCards) {
386 if (nCards < 1) {
387 nCards = 1;
388 }
389 minCards = nCards;
390 }
391
392 /**
393 * Merges copies of all cards from another header, provided they are not readily present in this header. That is, it
394 * merges only the non-conflicting or distinct header entries from the designated source (in contrast to
395 * {@link #updateLines(Header)}). All comment cards are merged also (since these can always appear multiple times,
396 * so they do not conflict). The merged entries are added at the end of the header, in the same order as they appear
397 * in the source. The merged entries will be copies of the cards in the original, such that subsequent modifications
398 * to the source will not affect this header or vice versa.
399 *
400 * @param source The header from which to inherit non-conflicting entries
401 *
402 * @since 1.19
403 *
404 * @see #updateLines(Header)
405 * @see #getDetachedCopy()
406 */
407 public void mergeDistinct(Header source) {
408 seekTail();
409
410 Cursor<String, HeaderCard> c = source.iterator();
411 while (c.hasNext()) {
412 HeaderCard card = c.next();
413 if (card.isCommentStyleCard() || !containsKey(card.getKey())) {
414 if (card.getKey().equals(Standard.SIMPLE.key()) || card.getKey().equals(Standard.XTENSION.key())) {
415 // Do not merge SIMPLE / XTENSION -- these are private matters...
416 continue;
417 }
418 addLine(card.copy());
419 }
420 }
421 }
422
423 /**
424 * Insert a new header card at the current position, deleting any prior occurence of the same card while maintaining
425 * the current position to point to after the newly inserted card.
426 *
427 * @param fcard The card to be inserted.
428 *
429 * @throws IllegalArgumentException if the current keyword checking mode does not allow the headercard with its
430 * standard keyword in the header.
431 *
432 * @see #setKeywordChecking(KeywordCheck)
433 */
434 public void addLine(HeaderCard fcard) throws IllegalArgumentException {
435 if (fcard == null) {
436 return;
437 }
438
439 if (fcard.getStandardKey() != null) {
440 checkKeyword(fcard.getStandardKey());
441 }
442
443 cursor().add(fcard);
444 }
445
446 /**
447 * <p>
448 * Sets the built-in standard keyword checking mode. When populating the header using {@link IFitsHeader} keywords
449 * the library will check if the given keyword is appropriate for the type of HDU that the header represents, and
450 * will throw an {@link IllegalArgumentException} if the specified keyword is not allowed for that type of HDU.
451 * </p>
452 * <p>
453 * This method changes the keyword checking mode for this header instance only. If you want to change the mode for
454 * all newly created headers globally, use {@link #setDefaultKeywordChecking(KeywordCheck)} instead.
455 * </p>
456 *
457 * @param mode The keyword checking mode to use.
458 *
459 * @see #getKeywordChecking()
460 * @see HeaderCard#setValueCheckingPolicy(nom.tam.fits.HeaderCard.ValueCheck)
461 *
462 * @since 1.19
463 */
464 public void setKeywordChecking(KeywordCheck mode) {
465 keyCheck = mode;
466 }
467
468 /**
469 * Sets the default mode of built-in standard keyword checking mode for new headers. When populating the header
470 * using {@link IFitsHeader} keywords the library will check if the given keyword is appropriate for the type of HDU
471 * that the header represents, and will throw an {@link IllegalArgumentException} if the specified keyword is not
472 * allowed for that type of HDU.
473 *
474 * @param mode The keyword checking policy to use.
475 *
476 * @see #setKeywordChecking(KeywordCheck)
477 * @see #getKeywordChecking()
478 * @see HeaderCard#setValueCheckingPolicy(nom.tam.fits.HeaderCard.ValueCheck)
479 *
480 * @since 1.19
481 */
482 public static void setDefaultKeywordChecking(KeywordCheck mode) {
483 defaultKeyCheck = mode;
484 }
485
486 /**
487 * Returns the current keyword checking mode.
488 *
489 * @return the current keyword checking mode
490 *
491 * @see #setKeywordChecking(KeywordCheck)
492 *
493 * @since 1.19
494 */
495 public final KeywordCheck getKeywordChecking() {
496 return keyCheck;
497 }
498
499 private void checkKeyword(IFitsHeader keyword) throws IllegalArgumentException {
500 if (keyCheck == KeywordCheck.NONE || owner == null) {
501 return;
502 }
503
504 if (keyCheck == KeywordCheck.STRICT
505 && (keyword.status() == IFitsHeader.SOURCE.MANDATORY || keyword.status() == IFitsHeader.SOURCE.INTEGRAL)) {
506 throw new IllegalArgumentException("Keyword " + keyword + " should be set by the library only");
507 }
508
509 switch (keyword.hdu()) {
510
511 case PRIMARY:
512 if (!owner.canBePrimary()) {
513 throw new IllegalArgumentException(
514 "Keyword " + keyword + " is a primary keyword and may not be used in extensions");
515 }
516 return;
517 case EXTENSION:
518 if (owner instanceof RandomGroupsHDU) {
519 throw new IllegalArgumentException(
520 "Keyword " + keyword + " is an extension keyword but random groups may only be primary");
521 }
522 return;
523 case IMAGE:
524 if (owner instanceof ImageHDU || owner instanceof RandomGroupsHDU) {
525 return;
526 }
527 break;
528 case GROUPS:
529 if (owner instanceof RandomGroupsHDU) {
530 return;
531 }
532 break;
533 case TABLE:
534 if (owner instanceof TableHDU) {
535 return;
536 }
537 break;
538 case ASCII_TABLE:
539 if (owner instanceof AsciiTableHDU) {
540 return;
541 }
542 break;
543 case BINTABLE:
544 if (owner instanceof BinaryTableHDU) {
545 return;
546 }
547 break;
548 default:
549 return;
550 }
551
552 throw new IllegalArgumentException(
553 "Keyword " + keyword.key() + " is not appropriate for " + owner.getClass().getName());
554 }
555
556 /**
557 * Add or replace a key with the given boolean value and its standardized comment. If the value is not compatible
558 * with the convention of the keyword, a warning message is logged but no exception is thrown (at this point). The
559 * new card will be placed at the current mark position, as set e.g. by {@link #findCard(IFitsHeader)}.
560 *
561 * @param key The header key.
562 * @param val The boolean value.
563 *
564 * @return the new card that was added.
565 *
566 * @throws HeaderCardException If the parameters cannot build a valid FITS card.
567 * @throws IllegalArgumentException If the keyword is invalid
568 *
569 * @see #addValue(String, Boolean, String)
570 */
571 public HeaderCard addValue(IFitsHeader key, Boolean val) throws HeaderCardException, IllegalArgumentException {
572 HeaderCard card = HeaderCard.create(key, val);
573 addLine(card);
574 return card;
575 }
576
577 /**
578 * Add or replace a key with the given double value and its standardized comment. If the value is not compatible
579 * with the convention of the keyword, a warning message is logged but no exception is thrown (at this point). The
580 * new card will be placed at the current mark position, as set e.g. by {@link #findCard(IFitsHeader)}.
581 *
582 * @param key The header key.
583 * @param val The double value.
584 *
585 * @return the new card that was added.
586 *
587 * @throws HeaderCardException If the parameters cannot build a valid FITS card.
588 * @throws IllegalArgumentException If the keyword is invalid
589 *
590 * @see #addValue(String, Number, String)
591 */
592 public HeaderCard addValue(IFitsHeader key, Number val) throws HeaderCardException, IllegalArgumentException {
593 HeaderCard card = HeaderCard.create(key, val);
594 addLine(card);
595 return card;
596 }
597
598 /**
599 * Add or replace a key with the given string value and its standardized comment. If the value is not compatible
600 * with the convention of the keyword, a warning message is logged but no exception is thrown (at this point). The
601 * new card will be placed at the current mark position, as set e.g. by {@link #findCard(IFitsHeader)}.
602 *
603 * @param key The header key.
604 * @param val The string value.
605 *
606 * @return the new card that was added.
607 *
608 * @throws HeaderCardException If the parameters cannot build a valid FITS card.
609 * @throws IllegalArgumentException If the keyword is invalid
610 *
611 * @see #addValue(String, String, String)
612 */
613 public HeaderCard addValue(IFitsHeader key, String val) throws HeaderCardException, IllegalArgumentException {
614 HeaderCard card = HeaderCard.create(key, val);
615 addLine(card);
616 return card;
617 }
618
619 /**
620 * Add or replace a key with the given complex value and its standardized comment. If the value is not compatible
621 * with the convention of the keyword, a warning message is logged but no exception is thrown (at this point). The
622 * new card will be placed at the current mark position, as set e.g. by {@link #findCard(IFitsHeader)}.
623 *
624 * @param key The header key.
625 * @param val The complex value.
626 *
627 * @return the new card that was added.
628 *
629 * @throws HeaderCardException If the parameters cannot build a valid FITS card.
630 * @throws IllegalArgumentException If the keyword is invalid
631 *
632 * @see #addValue(String, ComplexValue, String)
633 *
634 * @since 1.17
635 */
636 public HeaderCard addValue(IFitsHeader key, ComplexValue val) throws HeaderCardException, IllegalArgumentException {
637 HeaderCard card = HeaderCard.create(key, val);
638 addLine(card);
639 return card;
640 }
641
642 /**
643 * Add or replace a key with the given boolean value and comment. The new card will be placed at the current mark
644 * position, as set e.g. by {@link #findCard(String)}.
645 *
646 * @param key The header key.
647 * @param val The boolean value.
648 * @param comment A comment to append to the card.
649 *
650 * @return the new card that was added.
651 *
652 * @throws HeaderCardException If the parameters cannot build a valid FITS card.
653 *
654 * @see #addValue(IFitsHeader, Boolean)
655 * @see HeaderCard#HeaderCard(String, Boolean, String)
656 */
657 public HeaderCard addValue(String key, Boolean val, String comment) throws HeaderCardException {
658 HeaderCard hc = new HeaderCard(key, val, comment);
659 addLine(hc);
660 return hc;
661 }
662
663 /**
664 * Add or replace a key with the given number value and comment. The value will be represented in the header card
665 * with use the native precision of the value or at least {@link nom.tam.util.FlexFormat#DOUBLE_DECIMALS}, whichever
666 * fits in the available card space. Trailing zeroes will be ommitted. The new card will be placed at the current
667 * mark position, as set e.g. by {@link #findCard(String)}.
668 *
669 * @param key The header key.
670 * @param val The number value.
671 * @param comment A comment to append to the card.
672 *
673 * @return the new card that was added.
674 *
675 * @throws HeaderCardException If the parameters cannot build a valid FITS card.
676 *
677 * @see #addValue(String, Number, int, String)
678 * @see #addValue(IFitsHeader, Number)
679 * @see HeaderCard#HeaderCard(String, Number, String)
680 */
681 public HeaderCard addValue(String key, Number val, String comment) throws HeaderCardException {
682 HeaderCard hc = new HeaderCard(key, val, comment);
683 addLine(hc);
684 return hc;
685 }
686
687 /**
688 * Add or replace a key with the given number value and comment, using up to the specified decimal places after the
689 * leading figure. Trailing zeroes will be ommitted. The new card will be placed at the current mark position, as
690 * set e.g. by {@link #findCard(String)}.
691 *
692 * @param key The header key.
693 * @param val The number value.
694 * @param decimals The number of decimal places to show after the leading figure, or
695 * {@link nom.tam.util.FlexFormat#AUTO_PRECISION} to use the native precision of the
696 * value or at least {@link nom.tam.util.FlexFormat#DOUBLE_DECIMALS}, whichever fits
697 * in the available card space.
698 * @param comment A comment to append to the card.
699 *
700 * @return the new card that was added.
701 *
702 * @throws HeaderCardException If the parameters cannot build a valid FITS card.
703 *
704 * @see #addValue(String, Number, String)
705 * @see HeaderCard#HeaderCard(String, Number, int, String)
706 */
707 public HeaderCard addValue(String key, Number val, int decimals, String comment) throws HeaderCardException {
708 HeaderCard hc = new HeaderCard(key, val, decimals, comment);
709 addLine(hc);
710 return hc;
711 }
712
713 /**
714 * Add or replace a key with the given complex number value and comment. Trailing zeroes will be ommitted. The new
715 * card will be placed at the current mark position, as set e.g. by {@link #findCard(String)}.
716 *
717 * @param key The header keyword.
718 * @param val The complex number value.
719 * @param comment A comment to append to the card.
720 *
721 * @return the new card that was added.
722 *
723 * @throws HeaderCardException If the parameters cannot build a valid FITS card.
724 *
725 * @since 1.16
726 *
727 * @see #addValue(String, ComplexValue, int, String)
728 * @see HeaderCard#HeaderCard(String, ComplexValue, String)
729 */
730 public HeaderCard addValue(String key, ComplexValue val, String comment) throws HeaderCardException {
731 HeaderCard hc = new HeaderCard(key, val, comment);
732 addLine(hc);
733 return hc;
734 }
735
736 /**
737 * Add or replace a key with the given complex number value and comment, using up to the specified decimal places
738 * after the leading figure. Trailing zeroes will be ommitted. The new card will be placed at the current mark
739 * position, as set e.g. by {@link #findCard(String)}.
740 *
741 * @param key The header keyword.
742 * @param val The complex number value.
743 * @param decimals The number of decimal places to show after the leading figure, or
744 * {@link nom.tam.util.FlexFormat#AUTO_PRECISION} to use the native precision of the
745 * value, or at least {@link nom.tam.util.FlexFormat#DOUBLE_DECIMALS}, whichever
746 * fits in the available card space.
747 * @param comment A comment to append to the card.
748 *
749 * @return the new card that was added.
750 *
751 * @throws HeaderCardException If the parameters cannot build a valid FITS card.
752 *
753 * @since 1.16
754 *
755 * @see #addValue(String, ComplexValue, String)
756 * @see HeaderCard#HeaderCard(String, ComplexValue, int, String)
757 */
758 public HeaderCard addValue(String key, ComplexValue val, int decimals, String comment) throws HeaderCardException {
759 HeaderCard hc = new HeaderCard(key, val, decimals, comment);
760 addLine(hc);
761 return hc;
762 }
763
764 /**
765 * @deprecated Not supported by the FITS standard, so do not use. It was included due to a
766 * misreading of the standard itself. We will remove this method in the future.
767 *
768 * @param key The header key.
769 * @param val The integer value.
770 * @param comment A comment to append to the card.
771 *
772 * @return the new card that was added.
773 *
774 * @throws HeaderCardException If the parameters cannot build a valid FITS card.
775 *
776 * @since 1.16
777 *
778 * @see #addValue(String, Number, String)
779 * @see HeaderCard#createHexValueCard(String, long)
780 * @see #getHexValue(String)
781 */
782 @Deprecated
783 public HeaderCard addHexValue(String key, long val, String comment) throws HeaderCardException {
784 HeaderCard hc = HeaderCard.createHexValueCard(key, val, comment);
785 addLine(hc);
786 return hc;
787 }
788
789 /**
790 * Add or replace a key with the given string value and comment. The new card will be placed at the current mark
791 * position, as set e.g. by {@link #findCard(String)}.
792 *
793 * @param key The header key.
794 * @param val The string value.
795 * @param comment A comment to append to the card.
796 *
797 * @return the new card that was added.
798 *
799 * @throws HeaderCardException If the parameters cannot build a valid FITS card.
800 *
801 * @see #addValue(IFitsHeader, String)
802 * @see HeaderCard#HeaderCard(String, String, String)
803 */
804 public HeaderCard addValue(String key, String val, String comment) throws HeaderCardException {
805 HeaderCard hc = new HeaderCard(key, val, comment);
806 addLine(hc);
807 return hc;
808 }
809
810 /**
811 * get a builder for filling the header cards using the builder pattern.
812 *
813 * @param key the key for the first card.
814 *
815 * @return the builder for header cards.
816 */
817 public HeaderCardBuilder card(IFitsHeader key) {
818 return new HeaderCardBuilder(this, key);
819 }
820
821 /**
822 * Tests if the specified keyword is present in this table.
823 *
824 * @param key the keyword to be found.
825 *
826 * @return <code>true</code> if the specified keyword is present in this table; <code>false</code> otherwise.
827 */
828 public final boolean containsKey(IFitsHeader key) {
829 return cards.containsKey(key.key());
830 }
831
832 /**
833 * Tests if the specified keyword is present in this table.
834 *
835 * @param key the keyword to be found.
836 *
837 * @return <code>true</code> if the specified keyword is present in this table; <code>false</code> otherwise.
838 */
839 public final boolean containsKey(String key) {
840 return cards.containsKey(key);
841 }
842
843 /**
844 * Delete the card associated with the given key. Nothing occurs if the key is not found.
845 *
846 * @param key The header key.
847 */
848 public void deleteKey(IFitsHeader key) {
849 deleteKey(key.key());
850 }
851
852 /**
853 * Delete the card associated with the given key. Nothing occurs if the key is not found.
854 *
855 * @param key The header key.
856 */
857 public void deleteKey(String key) {
858 // AK: This version will not move the current position to the deleted
859 // key
860 if (containsKey(key)) {
861 cards.remove(cards.get(key));
862 }
863 }
864
865 /**
866 * Print the header to a given stream. Note that this method does not show reserved card space before the END
867 * keyword, and thus does not necessarily show the same layout as what would appear in a file.
868 *
869 * @param ps the stream to which the card images are dumped.
870 *
871 * @see #ensureCardSpace(int)
872 */
873 public void dumpHeader(PrintStream ps) {
874 Cursor<String, HeaderCard> iter = iterator();
875 while (iter.hasNext()) {
876 ps.println(iter.next());
877 }
878 }
879
880 /**
881 * Returns the card associated with a given key. Unlike {@link #findCard(IFitsHeader)}, it does not alter the mark
882 * position at which new cards are added.
883 *
884 * @param key the header key.
885 *
886 * @return <CODE>null</CODE> if the keyword could not be found; return the HeaderCard object otherwise.
887 *
888 * @see #getCard(String)
889 * @see #findCard(IFitsHeader)
890 *
891 * @since 1.18.1
892 */
893 public HeaderCard getCard(IFitsHeader key) {
894 return this.getCard(key.key());
895 }
896
897 /**
898 * Find the card associated with a given key. If found this sets the mark (cursor) to the card, otherwise it unsets
899 * the mark. The mark is where new cards will be added to the header by default. If you do not want to change the
900 * mark position, use {@link #getCard(IFitsHeader)} instead.
901 *
902 * @param key The header key.
903 *
904 * @return <CODE>null</CODE> if the keyword could not be found; return the HeaderCard object otherwise.
905 *
906 * @see #getCard(IFitsHeader)
907 * @see #findCard(String)
908 */
909 public HeaderCard findCard(IFitsHeader key) {
910 return this.findCard(key.key());
911 }
912
913 /**
914 * Returns the card associated with a given key. Unlike {@link #findCard(String)}, it does not alter the mark
915 * position at which new cards are added.
916 *
917 * @param key the header key.
918 *
919 * @return <CODE>null</CODE> if the keyword could not be found; return the HeaderCard object otherwise.
920 *
921 * @see #getCard(IFitsHeader)
922 * @see #findCard(String)
923 *
924 * @since 1.18.1
925 */
926 public HeaderCard getCard(String key) {
927 return cards.get(key);
928 }
929
930 /**
931 * Finds the card associated with a given key, and returns it. If found this sets the mark (cursor) to just before
932 * the card, such that {@link #nextCard()} will return that very same card on the first subsequent call. If the
933 * header contains no matching entry, the mark is reset to the tail of the header (the same as {@link #seekTail()}).
934 * The mark determines where new cards will be added to the header by default. If you do not want to alter the mark
935 * position, use {@link #getCard(String)} instead.
936 *
937 * @param key the header key.
938 *
939 * @return Returns the header entry for the given keyword, or <CODE>null</CODE> if the header has no such entry.
940 *
941 * @see #getCard(String)
942 * @see #findCard(String)
943 */
944 public HeaderCard findCard(String key) {
945 HeaderCard card = cards.get(key);
946 if (card != null) {
947 cursor().setKey(key);
948 } else {
949 cursor().end();
950 }
951 return card;
952 }
953
954 /************************************
955 * brief Collect the header cards that match a regular expression. This is useful if one needs to search for a
956 * keyword that is buried under some HIERARCH string conventions of unspecified depth. So to search for some key
957 * like "HIERARCH OBO SUBOBO MYOBO", which would appear with the key HIERARCH.OBO.SUBOBO.MYOBO in this FITS
958 * implementation, one could search with regex="HIER.*MYOBO" and find it, supposed FitsFactory.setUseHierarch(true)
959 * was called before creating the header.
960 *
961 * @param regex The generalized regular expression for the keyword search
962 *
963 * @return The list of header cards that match the regular expression.
964 *
965 * @since 1.19.1
966 */
967 public HeaderCard[] findCards(final String regex) {
968 /*
969 * The collection of header cards that match.
970 */
971 ArrayList<HeaderCard> crds = new ArrayList<>();
972
973 /*
974 * position pointer to start of card stack and loop over all header cards
975 */
976 nom.tam.util.Cursor<String, HeaderCard> iter = iterator();
977 while (iter.hasNext()) {
978 final HeaderCard card = iter.next();
979 /*
980 * compare with regular expression and add to output list if it does
981 */
982 if (card.getKey().matches(regex)) {
983 crds.add(card);
984 }
985 }
986
987 HeaderCard[] tmp = new HeaderCard[crds.size()];
988 return crds.toArray(tmp);
989 } /* findCards */
990
991 /**
992 * @deprecated Use {@link #findCard(String)} or {@link #getCard(String)} instead. Find the card associated with
993 * a given key.
994 *
995 * @param key The header key.
996 *
997 * @return <CODE>null</CODE> if the keyword could not be found; return the card image otherwise.
998 */
999 @Deprecated
1000 public String findKey(String key) {
1001 HeaderCard card = findCard(key);
1002 if (card == null) {
1003 return null;
1004 }
1005 return card.toString();
1006 }
1007
1008 /**
1009 * Get the bid decimal value associated with the given key.
1010 *
1011 * @deprecated The FITS header does not support decimal types beyond those that can be represented by a 64-bit
1012 * IEEE double-precision floating point value.
1013 *
1014 * @param key The header key.
1015 *
1016 * @return The associated value or 0.0 if not found.
1017 */
1018 @Deprecated
1019 public final BigDecimal getBigDecimalValue(IFitsHeader key) {
1020 return getBigDecimalValue(key.key());
1021 }
1022
1023 /**
1024 * Get the big decimal value associated with the given key.
1025 *
1026 * @deprecated The FITS header does not support decimal types beyond those that can be represented by a 64-bit
1027 * IEEE double-precision floating point value.
1028 *
1029 * @param key The header key.
1030 * @param dft The default value to return if the key cannot be found.
1031 *
1032 * @return the associated value.
1033 */
1034 @Deprecated
1035 public final BigDecimal getBigDecimalValue(IFitsHeader key, BigDecimal dft) {
1036 return getBigDecimalValue(key.key(), dft);
1037 }
1038
1039 /**
1040 * Get the big decimal value associated with the given key.
1041 *
1042 * @deprecated The FITS header does not support decimal types beyond those that can be represented by a 64-bit
1043 * IEEE double-precision floating point value.
1044 *
1045 * @param key The header key.
1046 *
1047 * @return The associated value or 0.0 if not found.
1048 */
1049 @Deprecated
1050 public final BigDecimal getBigDecimalValue(String key) {
1051 return getBigDecimalValue(key, BigDecimal.ZERO);
1052 }
1053
1054 /**
1055 * Get the big decimal value associated with the given key.
1056 *
1057 * @deprecated The FITS header does not support decimal types beyond those that can be represented by a 64-bit
1058 * IEEE double-precision floating point value.
1059 *
1060 * @param key The header key.
1061 * @param dft The default value to return if the key cannot be found.
1062 *
1063 * @return the associated value.
1064 */
1065 @Deprecated
1066 public BigDecimal getBigDecimalValue(String key, BigDecimal dft) {
1067 HeaderCard fcard = getCard(key);
1068 if (fcard == null) {
1069 return dft;
1070 }
1071 return fcard.getValue(BigDecimal.class, dft);
1072 }
1073
1074 /**
1075 * Get the big integer value associated with the given key.
1076 *
1077 * @deprecated The FITS header does not support integer types beyond those that can be represented by a 64-bit
1078 * integer.
1079 *
1080 * @param key The header key.
1081 *
1082 * @return the associated value or 0 if not found.
1083 */
1084 @Deprecated
1085 public final BigInteger getBigIntegerValue(IFitsHeader key) {
1086 return getBigIntegerValue(key.key());
1087 }
1088
1089 /**
1090 * Get the big integer value associated with the given key, or return a default value.
1091 *
1092 * @deprecated The FITS header does not support integer types beyond those that can be represented by a 64-bit
1093 * integer.
1094 *
1095 * @param key The header key.
1096 * @param dft The default value to be returned if the key cannot be found.
1097 *
1098 * @return the associated value.
1099 */
1100 @Deprecated
1101 public final BigInteger getBigIntegerValue(IFitsHeader key, BigInteger dft) {
1102 return getBigIntegerValue(key.key(), dft);
1103 }
1104
1105 /**
1106 * Get the big integer value associated with the given key.
1107 *
1108 * @deprecated The FITS header does not support integer types beyond those that can be represented by a 64-bit
1109 * integer.
1110 *
1111 * @param key The header key.
1112 *
1113 * @return The associated value or 0 if not found.
1114 */
1115 @Deprecated
1116 public final BigInteger getBigIntegerValue(String key) {
1117 return getBigIntegerValue(key, BigInteger.ZERO);
1118 }
1119
1120 /**
1121 * Get the big integer value associated with the given key.
1122 *
1123 * @deprecated The FITS header does not support integer types beyond those that can be represented by a 64-bit
1124 * integer.
1125 *
1126 * @param key The header key.
1127 * @param dft The default value to be returned if the key cannot be found.
1128 *
1129 * @return the associated value.
1130 */
1131 @Deprecated
1132 public BigInteger getBigIntegerValue(String key, BigInteger dft) {
1133 HeaderCard fcard = getCard(key);
1134 if (fcard == null) {
1135 return dft;
1136 }
1137 return fcard.getValue(BigInteger.class, dft);
1138 }
1139
1140 /**
1141 * Get the complex number value associated with the given key.
1142 *
1143 * @param key The header key.
1144 *
1145 * @return The associated value or {@link ComplexValue#ZERO} if not found.
1146 *
1147 * @since 1.16
1148 *
1149 * @see #getComplexValue(String, ComplexValue)
1150 * @see HeaderCard#getValue(Class, Object)
1151 * @see #addValue(String, ComplexValue, String)
1152 */
1153 public final ComplexValue getComplexValue(String key) {
1154 return getComplexValue(key, ComplexValue.ZERO);
1155 }
1156
1157 /**
1158 * Get the complex number value associated with the given key, or return a default value.
1159 *
1160 * @param key The header key.
1161 * @param dft The default value to return if the key cannot be found.
1162 *
1163 * @return the associated value.
1164 *
1165 * @since 1.16
1166 *
1167 * @see #getComplexValue(String)
1168 * @see HeaderCard#getValue(Class, Object)
1169 * @see #addValue(String, ComplexValue, String)
1170 */
1171 public ComplexValue getComplexValue(String key, ComplexValue dft) {
1172 HeaderCard fcard = getCard(key);
1173 if (fcard == null) {
1174 return dft;
1175 }
1176 return fcard.getValue(ComplexValue.class, dft);
1177 }
1178
1179 /**
1180 * Get the <CODE>boolean</CODE> value associated with the given key.
1181 *
1182 * @param key The header key.
1183 *
1184 * @return The value found, or false if not found or if the keyword is not a logical keyword.
1185 */
1186 public final boolean getBooleanValue(IFitsHeader key) {
1187 return getBooleanValue(key.key());
1188 }
1189
1190 /**
1191 * Get the <CODE>boolean</CODE> value associated with the given key.
1192 *
1193 * @param key The header key.
1194 * @param dft The value to be returned if the key cannot be found or if the parameter does not seem to be a
1195 * boolean.
1196 *
1197 * @return the associated value.
1198 */
1199 public final boolean getBooleanValue(IFitsHeader key, boolean dft) {
1200 return getBooleanValue(key.key(), dft);
1201 }
1202
1203 /**
1204 * Get the <CODE>boolean</CODE> value associated with the given key.
1205 *
1206 * @param key The header key.
1207 *
1208 * @return The value found, or false if not found or if the keyword is not a logical keyword.
1209 */
1210 public final boolean getBooleanValue(String key) {
1211 return getBooleanValue(key, false);
1212 }
1213
1214 /**
1215 * Get the <CODE>boolean</CODE> value associated with the given key.
1216 *
1217 * @param key The header key.
1218 * @param dft The value to be returned if the key cannot be found or if the parameter does not seem to be a
1219 * boolean.
1220 *
1221 * @return the associated value.
1222 */
1223 public boolean getBooleanValue(String key, boolean dft) {
1224 HeaderCard fcard = getCard(key);
1225 if (fcard == null) {
1226 return dft;
1227 }
1228 return fcard.getValue(Boolean.class, dft).booleanValue();
1229 }
1230
1231 /**
1232 * Get the n'th card image in the header
1233 *
1234 * @param n the card index to get
1235 *
1236 * @return the card image; return <CODE>null</CODE> if the n'th card does not exist.
1237 *
1238 * @deprecated An iterator from {@link #iterator(int)} or {@link #iterator()} should be used for sequential access
1239 * to the header.
1240 */
1241 @Deprecated
1242 public String getCard(int n) {
1243 if (n >= 0 && n < cards.size()) {
1244 return cards.get(n).toString();
1245 }
1246 return null;
1247 }
1248
1249 /**
1250 * Return the size of the data including any needed padding.
1251 *
1252 * @return the data segment size including any needed padding.
1253 */
1254 public long getDataSize() {
1255 return FitsUtil.addPadding(trueDataSize());
1256 }
1257
1258 /**
1259 * Get the <CODE>double</CODE> value associated with the given key.
1260 *
1261 * @param key The header key.
1262 *
1263 * @return The associated value or 0.0 if not found.
1264 */
1265 public final double getDoubleValue(IFitsHeader key) {
1266 return getDoubleValue(key.key());
1267 }
1268
1269 /**
1270 * Get the <CODE>double</CODE> value associated with the given key, or return a default value.
1271 *
1272 * @param key The header key.
1273 * @param dft The default value to return if the key cannot be found.
1274 *
1275 * @return the associated value.
1276 */
1277 public final double getDoubleValue(IFitsHeader key, double dft) {
1278 return getDoubleValue(key.key(), dft);
1279 }
1280
1281 /**
1282 * Get the <CODE>double</CODE> value associated with the given key.
1283 *
1284 * @param key The header key.
1285 *
1286 * @return The associated value or 0.0 if not found.
1287 */
1288 public final double getDoubleValue(String key) {
1289 return getDoubleValue(key, 0.0);
1290 }
1291
1292 /**
1293 * Get the <CODE>double</CODE> value associated with the given key, or return a default value.
1294 *
1295 * @param key The header key.
1296 * @param dft The default value to return if the key cannot be found.
1297 *
1298 * @return the associated value.
1299 */
1300 public double getDoubleValue(String key, double dft) {
1301 HeaderCard fcard = getCard(key);
1302 if (fcard == null) {
1303 return dft;
1304 }
1305 return fcard.getValue(Double.class, dft).doubleValue();
1306 }
1307
1308 /**
1309 * <p>
1310 * Returns the list of duplicate cards in the order they appeared in the parsed header. You can access the first
1311 * occurence of each of every duplicated FITS keyword using the usual <code>Header.getValue()</code>, and find
1312 * further occurrences in the list returned here.
1313 * </p>
1314 * <p>
1315 * The FITS standared strongly discourages using the keywords multiple times with assigned values, and specifies
1316 * that the values of such keywords are undefined by definitions. Our library is thus far more tolerant than the
1317 * FITS standard, allowing you to access each and every value that was specified for the same keyword.
1318 * </p>
1319 * <p>
1320 * On the other hand FITS does not limit how many times you can add comment-style keywords to a header. If you must
1321 * used the same keyword multiple times in your header, you should consider using comment-style entries instead.
1322 * </p>
1323 *
1324 * @return the list of duplicate cards. Note that when the header is read in, only the last entry for a given
1325 * keyword is retained in the active header. This method returns earlier cards that have been discarded
1326 * in the order in which they were encountered in the header. It is possible for there to be many cards
1327 * with the same keyword in this list.
1328 *
1329 * @see #hadDuplicates()
1330 * @see #getDuplicateKeySet()
1331 */
1332 public List<HeaderCard> getDuplicates() {
1333 return duplicates;
1334 }
1335
1336 /**
1337 * Returns the set of keywords that had more than one value assignment in the parsed header.
1338 *
1339 * @return the set of header keywords that were assigned more than once in the same header, or <code>null</code> if
1340 * there were no duplicate assignments.
1341 *
1342 * @see #hadDuplicates()
1343 * @see #getDuplicates()
1344 *
1345 * @since 1.17
1346 */
1347 public Set<String> getDuplicateKeySet() {
1348 return dupKeys;
1349 }
1350
1351 @Override
1352 public long getFileOffset() {
1353 return fileOffset;
1354 }
1355
1356 /**
1357 * Get the <CODE>float</CODE> value associated with the given key.
1358 *
1359 * @param key The header key.
1360 *
1361 * @return The associated value or 0.0 if not found.
1362 */
1363 public final float getFloatValue(IFitsHeader key) {
1364 return getFloatValue(key.key());
1365
1366 }
1367
1368 /**
1369 * Get the <CODE>float</CODE> value associated with the given key, or return a default value.
1370 *
1371 * @return the <CODE>float</CODE> value associated with the given key.
1372 *
1373 * @param key The header key.
1374 * @param dft The value to be returned if the key is not found.
1375 */
1376 public final float getFloatValue(IFitsHeader key, float dft) {
1377 return getFloatValue(key.key(), dft);
1378 }
1379
1380 /**
1381 * Get the <CODE>float</CODE> value associated with the given key.
1382 *
1383 * @param key The header key.
1384 *
1385 * @return The associated value or 0.0 if not found.
1386 */
1387 public final float getFloatValue(String key) {
1388 return getFloatValue(key, 0.0F);
1389 }
1390
1391 /**
1392 * Get the <CODE>float</CODE> value associated with the given key, or return a default value.
1393 *
1394 * @return the <CODE>float</CODE> value associated with the given key.
1395 *
1396 * @param key The header key.
1397 * @param dft The value to be returned if the key is not found.
1398 */
1399 public float getFloatValue(String key, float dft) {
1400 HeaderCard fcard = getCard(key);
1401 if (fcard == null) {
1402 return dft;
1403 }
1404 return fcard.getValue(Float.class, dft).floatValue();
1405 }
1406
1407 /**
1408 * Get the <CODE>int</CODE> value associated with the given key.
1409 *
1410 * @param key The header key.
1411 *
1412 * @return The associated value or 0 if not found.
1413 */
1414 public final int getIntValue(IFitsHeader key) {
1415 return (int) getLongValue(key);
1416 }
1417
1418 /**
1419 * Get the <CODE>int</CODE> value associated with the given key, or return a default value.
1420 *
1421 * @return the value associated with the key as an int.
1422 *
1423 * @param key The header key.
1424 * @param dft The value to be returned if the key is not found.
1425 */
1426 public final int getIntValue(IFitsHeader key, int dft) {
1427 return (int) getLongValue(key, dft);
1428 }
1429
1430 /**
1431 * Get the <CODE>int</CODE> value associated with the given key.
1432 *
1433 * @param key The header key.
1434 *
1435 * @return The associated value or 0 if not found.
1436 */
1437 public final int getIntValue(String key) {
1438 return (int) getLongValue(key);
1439 }
1440
1441 /**
1442 * Get the <CODE>int</CODE> value associated with the given key, or return a default value.
1443 *
1444 * @return the value associated with the key as an int.
1445 *
1446 * @param key The header key.
1447 * @param dft The value to be returned if the key is not found.
1448 */
1449 public int getIntValue(String key, int dft) {
1450 return (int) getLongValue(key, dft);
1451 }
1452
1453 /**
1454 * Get the n'th key in the header.
1455 *
1456 * @param n the index of the key
1457 *
1458 * @return the card image; return <CODE>null</CODE> if the n'th key does not exist.
1459 *
1460 * @deprecated An iterator from {@link #iterator(int)} or {@link #iterator()} should be used for sequential access
1461 * to the header.
1462 */
1463 @Deprecated
1464 public String getKey(int n) {
1465 if (n >= 0 && n < cards.size()) {
1466 return cards.get(n).getKey();
1467 }
1468 return null;
1469
1470 }
1471
1472 /**
1473 * Get the <CODE>long</CODE> value associated with the given key.
1474 *
1475 * @param key The header key.
1476 *
1477 * @return The associated value or 0 if not found.
1478 */
1479 public final long getLongValue(IFitsHeader key) {
1480 return getLongValue(key.key());
1481 }
1482
1483 /**
1484 * Get the <CODE>long</CODE> value associated with the given key, or return a default value.
1485 *
1486 * @param key The header key.
1487 * @param dft The default value to be returned if the key cannot be found.
1488 *
1489 * @return the associated value.
1490 */
1491 public final long getLongValue(IFitsHeader key, long dft) {
1492 return getLongValue(key.key(), dft);
1493 }
1494
1495 /**
1496 * Get the <CODE>long</CODE> value associated with the given key.
1497 *
1498 * @param key The header key.
1499 *
1500 * @return The associated value or 0 if not found.
1501 */
1502 public final long getLongValue(String key) {
1503 return getLongValue(key, 0L);
1504 }
1505
1506 /**
1507 * Get the <CODE>long</CODE> value associated with the given key, or return a default value.
1508 *
1509 * @param key The header key.
1510 * @param dft The default value to be returned if the key cannot be found.
1511 *
1512 * @return the associated value.
1513 */
1514 public long getLongValue(String key, long dft) {
1515 HeaderCard fcard = getCard(key);
1516 if (fcard == null) {
1517 return dft;
1518 }
1519 return fcard.getValue(Long.class, dft).longValue();
1520 }
1521
1522 /**
1523 * @deprecated Not supported by the FITS standard, so do not use. It was included due to a misreading of the
1524 * standard itself.
1525 *
1526 * @param key The header key.
1527 *
1528 * @return The associated value or 0 if not found.
1529 *
1530 * @since 1.16
1531 *
1532 * @see #getHexValue(String, long)
1533 * @see HeaderCard#getHexValue()
1534 * @see #addHexValue(String, long, String)
1535 */
1536 @Deprecated
1537 public final long getHexValue(String key) {
1538 return getHexValue(key, 0L);
1539 }
1540
1541 /**
1542 * @deprecated Not supported by the FITS standard, so do not use. It was included due to a misreading of the
1543 * standard itself.
1544 *
1545 * @param key The header key.
1546 * @param dft The default value to be returned if the key cannot be found.
1547 *
1548 * @return the associated value.
1549 *
1550 * @since 1.16
1551 *
1552 * @see #getHexValue(String)
1553 * @see HeaderCard#getHexValue()
1554 * @see #addHexValue(String, long, String)
1555 */
1556 @Deprecated
1557 public long getHexValue(String key, long dft) {
1558 HeaderCard fcard = getCard(key);
1559 if (fcard == null) {
1560 return dft;
1561 }
1562 try {
1563 return fcard.getHexValue();
1564 } catch (NumberFormatException e) {
1565 return dft;
1566 }
1567 }
1568
1569 /**
1570 * Returns the nominal number of currently defined cards in this header. Each card can consist of one or more
1571 * 80-character wide header records.
1572 *
1573 * @return the number of nominal cards in the header
1574 *
1575 * @see #getNumberOfPhysicalCards()
1576 */
1577 public int getNumberOfCards() {
1578 return cards.size();
1579 }
1580
1581 /**
1582 * Returns the number of 80-character header records in this header, including an END marker (whether or not it is
1583 * currently contained).
1584 *
1585 * @return the number of physical cards in the header, including the END marker.
1586 *
1587 * @see #getNumberOfCards()
1588 * @see #getSize()
1589 */
1590 public int getNumberOfPhysicalCards() {
1591 int count = 0;
1592 for (HeaderCard card : cards) {
1593 count += card.cardSize();
1594 }
1595
1596 // AK: Count the END card, which may not have been added yet...
1597 if (!containsKey(END)) {
1598 count++;
1599 }
1600
1601 return count;
1602 }
1603
1604 /**
1605 * Returns the minimum number of bytes that will be written by this header, either as the original byte size of a
1606 * header that was read, or else the minimum preallocated capacity after setting {@link #ensureCardSpace(int)}.
1607 *
1608 * @return the minimum byte size for this header. The actual header may take up more space than that (but never
1609 * less!), depending on the number of cards contained.
1610 *
1611 * @since 1.16
1612 *
1613 * @see #ensureCardSpace(int)
1614 * @see #read(ArrayDataInput)
1615 */
1616 public long getMinimumSize() {
1617 return FitsUtil.addPadding((long) minCards * HeaderCard.FITS_HEADER_CARD_SIZE);
1618 }
1619
1620 /**
1621 * @deprecated <i>for internal use</i>) It should be a private method in the future. Returns the original size of
1622 * the header in the stream from which it was read.
1623 *
1624 * @return the size of the original header in bytes, or 0 if the header was not read from a stream.
1625 *
1626 * @see #read(ArrayDataInput)
1627 * @see #getMinimumSize()
1628 */
1629 @Deprecated
1630 public final long getOriginalSize() {
1631 return readSize;
1632 }
1633
1634 @Override
1635 public final long getSize() {
1636 if (!isValidHeader()) {
1637 return 0;
1638 }
1639
1640 return FitsUtil
1641 .addPadding((long) Math.max(minCards, getNumberOfPhysicalCards()) * HeaderCard.FITS_HEADER_CARD_SIZE);
1642 }
1643
1644 /**
1645 * Get the <CODE>String</CODE> value associated with the given standard key.
1646 *
1647 * @param key The standard header key.
1648 *
1649 * @return The associated value or null if not found or if the value is not a string.
1650 *
1651 * @see #getStringValue(String)
1652 * @see #getStringValue(IFitsHeader, String)
1653 */
1654 public final String getStringValue(IFitsHeader key) {
1655 return getStringValue(key.key());
1656 }
1657
1658 /**
1659 * Get the <CODE>String</CODE> value associated with the given standard key, or return a default value.
1660 *
1661 * @param key The standard header key.
1662 * @param dft The default value.
1663 *
1664 * @return The associated value or the default value if not found or if the value is not a string.
1665 *
1666 * @see #getStringValue(String, String)
1667 * @see #getStringValue(IFitsHeader)
1668 */
1669 public final String getStringValue(IFitsHeader key, String dft) {
1670 return getStringValue(key.key(), dft);
1671 }
1672
1673 /**
1674 * Get the <CODE>String</CODE> value associated with the given key.
1675 *
1676 * @param key The header key.
1677 *
1678 * @return The associated value or null if not found or if the value is not a string.
1679 *
1680 * @see #getStringValue(IFitsHeader)
1681 * @see #getStringValue(String, String)
1682 */
1683 public final String getStringValue(String key) {
1684 return getStringValue(key, null);
1685 }
1686
1687 /**
1688 * Get the <CODE>String</CODE> value associated with the given key, or return a default value.
1689 *
1690 * @param key The header key.
1691 * @param dft The default value.
1692 *
1693 * @return The associated value or the default value if not found or if the value is not a string.
1694 *
1695 * @see #getStringValue(IFitsHeader, String)
1696 * @see #getStringValue(String)
1697 */
1698 public String getStringValue(String key, String dft) {
1699
1700 HeaderCard fcard = getCard(key);
1701 if (fcard == null || !fcard.isStringValue()) {
1702 return dft;
1703 }
1704
1705 return fcard.getValue();
1706 }
1707
1708 /**
1709 * Checks if the header had duplicate assignments in the FITS.
1710 *
1711 * @return Were duplicate header keys found when this record was read in?
1712 */
1713 public boolean hadDuplicates() {
1714 return duplicates != null;
1715 }
1716
1717 /**
1718 * Adds a line to the header using the COMMENT style, i.e., no '=' in column 9. The comment text may be truncated to
1719 * fit into a single record, which is returned. Alternatively, you can split longer comments among multiple
1720 * consecutive cards of the same type by {@link #insertCommentStyleMultiline(String, String)}.
1721 *
1722 * @param key The comment style header keyword, or <code>null</code> for an empty comment line.
1723 * @param comment A string comment to follow. Illegal characters will be replaced by '?' and the comment may be
1724 * truncated to fit into the card-space (71 characters).
1725 *
1726 * @return The new card that was inserted, or <code>null</code> if the keyword itself was invalid or the
1727 * comment was <code>null</code>.
1728 *
1729 * @see #insertCommentStyleMultiline(String, String)
1730 * @see HeaderCard#createCommentStyleCard(String, String)
1731 */
1732 public HeaderCard insertCommentStyle(String key, String comment) {
1733 if (comment == null) {
1734 comment = "";
1735 } else if (comment.length() > HeaderCard.MAX_COMMENT_CARD_COMMENT_LENGTH) {
1736 comment = comment.substring(0, HeaderCard.MAX_COMMENT_CARD_COMMENT_LENGTH);
1737 LOG.warning("Truncated comment to fit card: [" + comment + "]");
1738 }
1739
1740 try {
1741 HeaderCard hc = HeaderCard.createCommentStyleCard(key, HeaderCard.sanitize(comment));
1742 cursor().add(hc);
1743 return hc;
1744 } catch (HeaderCardException e) {
1745 LOG.log(Level.WARNING, "Ignoring comment card with invalid key [" + HeaderCard.sanitize(key) + "]", e);
1746 return null;
1747 }
1748 }
1749
1750 /**
1751 * Adds a line to the header using the COMMENT style, i.e., no '=' in column 9. If the comment does not fit in a
1752 * single record, then it will be split (wrapped) among multiple consecutive records with the same keyword. Wrapped
1753 * lines will end with '&' (not itself a standard) to indicate comment cards that might belong together.
1754 *
1755 * @param key The comment style header keyword, or <code>null</code> for an empty comment line.
1756 * @param comment A string comment to follow. Illegal characters will be replaced by '?' and the comment may be
1757 * split among multiple records as necessary to be fully preserved.
1758 *
1759 * @return The number of cards inserted.
1760 *
1761 * @since 1.16
1762 *
1763 * @see #insertCommentStyle(String, String)
1764 * @see #insertComment(String)
1765 * @see #insertUnkeyedComment(String)
1766 * @see #insertHistory(String)
1767 */
1768 public int insertCommentStyleMultiline(String key, String comment) {
1769
1770 // Empty comments must have at least one space char to write at least one
1771 // comment card...
1772 if ((comment == null) || comment.isEmpty()) {
1773 comment = " ";
1774 }
1775
1776 int n = 0;
1777
1778 for (int from = 0; from < comment.length();) {
1779 int to = from + HeaderCard.MAX_COMMENT_CARD_COMMENT_LENGTH;
1780 String part = null;
1781 if (to < comment.length()) {
1782 part = comment.substring(from, --to) + "&";
1783 } else {
1784 part = comment.substring(from);
1785 }
1786
1787 if (insertCommentStyle(key, part) == null) {
1788 return n;
1789 }
1790 from = to;
1791 n++;
1792 }
1793
1794 return n;
1795 }
1796
1797 /**
1798 * Adds one or more consecutive COMMENT records, wrapping the comment text as necessary.
1799 *
1800 * @param value The comment.
1801 *
1802 * @return The number of consecutive COMMENT cards that were inserted
1803 *
1804 * @see #insertCommentStyleMultiline(String, String)
1805 * @see #insertUnkeyedComment(String)
1806 * @see #insertHistory(String)
1807 * @see HeaderCard#createCommentCard(String)
1808 */
1809 public int insertComment(String value) {
1810 return insertCommentStyleMultiline(COMMENT.key(), value);
1811 }
1812
1813 /**
1814 * Adds one or more consecutive comment records with no keyword (bytes 1-9 left blank), wrapping the comment text as
1815 * necessary.
1816 *
1817 * @param value The comment.
1818 *
1819 * @return The number of consecutive comment-style cards with no keyword (blank keyword) that were inserted.
1820 *
1821 * @since 1.16
1822 *
1823 * @see #insertCommentStyleMultiline(String, String)
1824 * @see #insertComment(String)
1825 * @see #insertHistory(String)
1826 * @see HeaderCard#createUnkeyedCommentCard(String)
1827 * @see #insertBlankCard()
1828 */
1829 public int insertUnkeyedComment(String value) {
1830 return insertCommentStyleMultiline(BLANKS.key(), value);
1831 }
1832
1833 /**
1834 * Adds a blank card into the header.
1835 *
1836 * @since 1.16
1837 *
1838 * @see #insertUnkeyedComment(String)
1839 */
1840 public void insertBlankCard() {
1841 insertCommentStyle(null, null);
1842 }
1843
1844 /**
1845 * Adds one or more consecutive a HISTORY records, wrapping the comment text as necessary.
1846 *
1847 * @param value The history record.
1848 *
1849 * @return The number of consecutive HISTORY cards that were inserted
1850 *
1851 * @see #insertCommentStyleMultiline(String, String)
1852 * @see #insertComment(String)
1853 * @see #insertUnkeyedComment(String)
1854 * @see HeaderCard#createHistoryCard(String)
1855 */
1856 public int insertHistory(String value) {
1857 return insertCommentStyleMultiline(HISTORY.key(), value);
1858 }
1859
1860 /**
1861 * Returns a cursor-based iterator for this header's entries starting at the first entry.
1862 *
1863 * @return an iterator over the header cards
1864 */
1865 public Cursor<String, HeaderCard> iterator() {
1866 return cards.iterator(0);
1867 }
1868
1869 /**
1870 * Returns a cursor-based iterator for this header's entries.
1871 *
1872 * @deprecated We should never use indexed access to the header. This function will be removed in 2.0.
1873 *
1874 * @return an iterator over the header cards starting at an index
1875 *
1876 * @param index the card index to start the iterator
1877 */
1878 @Deprecated
1879 public Cursor<String, HeaderCard> iterator(int index) {
1880 return cards.iterator(index);
1881 }
1882
1883 /**
1884 * Return the iterator that represents the current position in the header. This provides a connection between
1885 * editing headers through Header add/append/update methods, and via Cursors, which can be used side-by-side while
1886 * maintaining desired card ordering. For the reverse direction ( translating iterator position to current position
1887 * in the header), we can just use findCard().
1888 *
1889 * @return the iterator representing the current position in the header.
1890 *
1891 * @see #iterator()
1892 */
1893 private Cursor<String, HeaderCard> cursor() {
1894 return cards.cursor();
1895 }
1896
1897 /**
1898 * Move the cursor to the end of the header. Subsequently, all <code>addValue()</code> calls will add new cards to
1899 * the end of the header.
1900 *
1901 * @return the cursor after it has been repositioned to the end
1902 *
1903 * @since 1.18.1
1904 *
1905 * @see #seekTail()
1906 * @see #findCard(String)
1907 * @see #nextCard()
1908 */
1909 public Cursor<String, HeaderCard> seekHead() {
1910 Cursor<String, HeaderCard> c = cursor();
1911
1912 while (c.hasPrev()) {
1913 c.prev();
1914 }
1915
1916 return c;
1917 }
1918
1919 /**
1920 * Move the cursor to the end of the header. Subsequently, all <code>addValue()</code> calls will add new cards to
1921 * the end of the header.
1922 *
1923 * @return the cursor after it has been repositioned to the end
1924 *
1925 * @since 1.18.1
1926 *
1927 * @see #seekHead()
1928 * @see #findCard(String)
1929 */
1930 public Cursor<String, HeaderCard> seekTail() {
1931 cursor().end();
1932 return cursor();
1933 }
1934
1935 /**
1936 * @deprecated (<i>for internal use</i>) Normally we either want to write a Java object to FITS (in
1937 * which case we have the dataand want to make a header for it), or we read some data
1938 * from a FITS input. In either case, there is no benefit of exposing such a function
1939 * as this to the user.
1940 *
1941 * @return Create the data element corresponding to the current header
1942 *
1943 * @throws FitsException if the header did not contain enough information to detect the type of the data
1944 */
1945 @Deprecated
1946 public Data makeData() throws FitsException {
1947 return FitsFactory.dataFactory(this);
1948 }
1949
1950 /**
1951 * Returns the header card at the currently set mark position and increments the mark position by one. The mark
1952 * position determines the location at which new entries are added to the header. The mark is set either to just
1953 * prior a particular card (e.g. via {@link #findCard(IFitsHeader)}.
1954 *
1955 * @return the next card in the Header using the built-in iterator
1956 *
1957 * @see #prevCard()
1958 * @see #findCard(IFitsHeader)
1959 * @see #findCard(String)
1960 * @see #seekHead()
1961 */
1962 public HeaderCard nextCard() {
1963 if (cursor().hasNext()) {
1964 return cursor().next();
1965 }
1966 return null;
1967 }
1968
1969 /**
1970 * Returns the header card prior to the currently set mark position and decrements the mark position by one. The
1971 * mark position determines the location at which new entries are added to the header. The mark is set either to
1972 * just prior a particular card (e.g. via {@link #findCard(IFitsHeader)}.
1973 *
1974 * @return the next card in the Header using the built-in iterator
1975 *
1976 * @see #nextCard()
1977 * @see #findCard(IFitsHeader)
1978 * @see #findCard(String)
1979 * @see #seekHead()
1980 *
1981 * @since 1.18.1
1982 */
1983 public HeaderCard prevCard() {
1984 if (cursor().hasPrev()) {
1985 return cursor().prev();
1986 }
1987 return null;
1988 }
1989
1990 /**
1991 * Create a header which points to the given data object.
1992 *
1993 * @param o The data object to be described.
1994 *
1995 * @throws FitsException if the data was not valid for this header.
1996 *
1997 * @deprecated Use the appropriate <code>Header</code> constructor instead. Will remove in a future
1998 * releae.
1999 */
2000 @Deprecated
2001 public void pointToData(Data o) throws FitsException {
2002 o.fillHeader(this);
2003 }
2004
2005 /**
2006 * Remove all cards and reset the header to its default status.
2007 */
2008 private void clear() {
2009 cards.clear();
2010 duplicates = null;
2011 dupKeys = null;
2012 readSize = 0;
2013 fileOffset = -1;
2014 minCards = 0;
2015 }
2016
2017 /**
2018 * Checks if the header is empty, that is if it contains no cards at all.
2019 *
2020 * @return <code>true</code> if the header contains no cards, otherwise <code>false</code>.
2021 *
2022 * @since 1.16
2023 */
2024 public boolean isEmpty() {
2025 return cards.isEmpty();
2026 }
2027
2028 /**
2029 * <p>
2030 * Reads new header data from an input, discarding any prior content.
2031 * </p>
2032 * <p>
2033 * As of 1.16, the header is ensured to (re)write at least the same number of cards as before, padding with blanks
2034 * as necessary, unless the user resets the preallocated card space with a call to {@link #ensureCardSpace(int)}.
2035 * </p>
2036 *
2037 * @param dis The input stream to read the data from.
2038 *
2039 * @throws TruncatedFileException the the stream ended prematurely
2040 * @throws IOException if the operation failed
2041 *
2042 * @see #ensureCardSpace(int)
2043 */
2044 @Override
2045 public void read(ArrayDataInput dis) throws TruncatedFileException, IOException {
2046 // AK: Start afresh, in case the header had prior contents from before.
2047 clear();
2048
2049 if (dis instanceof RandomAccess) {
2050 fileOffset = FitsUtil.findOffset(dis);
2051 } else {
2052 fileOffset = -1;
2053 }
2054
2055 if (dis instanceof FitsInputStream) {
2056 ((FitsInputStream) dis).nextChecksum();
2057 }
2058 streamSum = -1L;
2059
2060 int trailingBlanks = 0;
2061 minCards = 0;
2062
2063 HeaderCardCountingArrayDataInput cardCountingArray = new HeaderCardCountingArrayDataInput(dis);
2064 try {
2065 for (;;) {
2066 HeaderCard fcard = new HeaderCard(cardCountingArray);
2067 minCards += fcard.cardSize();
2068
2069 // AK: Note, 'key' can never be null, as per contract of getKey(). So no need to check...
2070 String key = fcard.getKey();
2071
2072 if (isEmpty()) {
2073 checkFirstCard(key);
2074 } else if (fcard.isBlank()) {
2075 // AK: We don't add the trailing blank cards, but keep count of them.
2076 // (esp. in case the aren't trailing...)
2077 trailingBlanks++;
2078 continue;
2079 } else if (END.key().equals(key)) {
2080 addLine(fcard);
2081 break; // Out of reading the header.
2082 } else if (LONGSTRN.key().equals(key)) {
2083 // We don't check the value here. If the user
2084 // wants to be sure that long strings are disabled,
2085 // they can call setLongStringsEnabled(false) after
2086 // reading the header.
2087 FitsFactory.setLongStringsEnabled(true);
2088 }
2089
2090 // AK: The preceding blank spaces were internal, not trailing
2091 // so add them back in now...
2092 for (int i = 0; i < trailingBlanks; i++) {
2093 insertBlankCard();
2094 }
2095 trailingBlanks = 0;
2096
2097 if (cards.containsKey(key)) {
2098 addDuplicate(cards.get(key));
2099 }
2100
2101 addLine(fcard);
2102 }
2103 } catch (EOFException e) {
2104 // Normal end-of-file before END key...
2105 throw e;
2106 } catch (Exception e) {
2107 if (isEmpty() && FitsFactory.getAllowTerminalJunk()) {
2108 // If this happened where we expect a new header to start, then
2109 // treat is as if end-of-file if terminal junk is allowed
2110 forceEOF(
2111 "Junk detected where header was expected to start" + ((fileOffset > 0) ? ": at " + fileOffset : ""),
2112 e);
2113 }
2114 if (e instanceof TruncatedFileException) {
2115 throw (TruncatedFileException) e;
2116 }
2117 throw new IOException("Invalid FITS Header" + (isEmpty() ? e :
2118 ":\n\n --> Try FitsFactory.setAllowTerminalJunk(true) prior to reading to work around.\n"), e);
2119 }
2120
2121 if (fileOffset >= 0) {
2122 input = dis;
2123 }
2124
2125 ensureCardSpace(cardCountingArray.getPhysicalCardsRead());
2126 readSize = FitsUtil.addPadding((long) minCards * HeaderCard.FITS_HEADER_CARD_SIZE);
2127
2128 // Read to the end of the current FITS block.
2129 //
2130 try {
2131 dis.skipAllBytes(FitsUtil.padding(minCards * HeaderCard.FITS_HEADER_CARD_SIZE));
2132 } catch (EOFException e) {
2133 // No biggy. We got a complete header just fine, it's only that there was no
2134 // padding before EOF. We'll just log that, but otherwise keep going.
2135 LOG.log(Level.WARNING, "Premature end-of-file: no padding after header.", e);
2136 }
2137
2138 if (dis instanceof FitsInputStream) {
2139 streamSum = ((FitsInputStream) dis).nextChecksum();
2140 }
2141
2142 // AK: Log if the file ends before the expected end-of-header position.
2143 if (Fits.checkTruncated(dis)) {
2144 // No biggy. We got a complete header just fine, it's only that there was no
2145 // padding before EOF. We'll just log that, but otherwise keep going.
2146 LOG.warning("Premature end-of-file: no padding after header.");
2147 }
2148
2149 // Move the cursor to after the last card -- this is where new cards will be added.
2150 seekTail();
2151 }
2152
2153 /**
2154 * Returns the random-accessible input from which this header was read, or <code>null</code> if the header is not
2155 * associated with an input, or the input is not random accessible.
2156 *
2157 * @return the random-accessible input associated with this header or <code>null</code>
2158 *
2159 * @see #read(ArrayDataInput)
2160 *
2161 * @since 1.18.1
2162 */
2163 RandomAccess getRandomAccessInput() {
2164 return (input instanceof RandomAccess) ? (RandomAccess) input : null;
2165 }
2166
2167 /**
2168 * Returns the checksum value calculated duting reading from a stream. It is only populated when reading from
2169 * {@link FitsInputStream} imputs, and never from other types of inputs. Valid values are greater or equal to zero.
2170 * Thus, the return value will be <code>-1L</code> to indicate an invalid (unpopulated) checksum.
2171 *
2172 * @return the non-negative checksum calculated for the data read from a stream, or else <code>-1L</code> if the
2173 * data was not read from the stream.
2174 *
2175 * @see FitsInputStream
2176 * @see Data#getStreamChecksum()
2177 *
2178 * @since 1.18.1
2179 */
2180 final long getStreamChecksum() {
2181 return streamSum;
2182 }
2183
2184 /**
2185 * Forces an EOFException to be thrown when some other exception happened, essentially treating the exception to
2186 * force a normal end the reading of the header.
2187 *
2188 * @param message the message to log.
2189 * @param cause the exception encountered while reading the header
2190 *
2191 * @throws EOFException the EOFException we'll throw instead.
2192 */
2193 private void forceEOF(String message, Exception cause) throws EOFException {
2194 LOG.log(Level.WARNING, message, cause);
2195 throw new EOFException("Forced EOF at " + fileOffset + " due to: " + message);
2196 }
2197
2198 /**
2199 * Delete a key.
2200 *
2201 * @param key The header key.
2202 *
2203 * @throws HeaderCardException if the operation failed
2204 *
2205 * @deprecated (<i>duplicate method</i>) Use {@link #deleteKey(String)} instead.
2206 */
2207 @Deprecated
2208 public void removeCard(String key) throws HeaderCardException {
2209 deleteKey(key);
2210 }
2211
2212 @Override
2213 public boolean reset() {
2214 try {
2215 FitsUtil.reposition(input, fileOffset);
2216 return true;
2217 } catch (Exception e) {
2218 LOG.log(Level.WARNING, "Exception while repositioning " + input, e);
2219 return false;
2220 }
2221 }
2222
2223 /**
2224 * @deprecated Use {@link #ensureCardSpace(int)} with 1 as the argument instead.
2225 * <p>
2226 * Resets any prior preallocated header space, such as was explicitly set by
2227 * {@link #ensureCardSpace(int)}, or when the header was read from a stream to ensure it remains
2228 * rewritable, if possible.
2229 * </p>
2230 * <p>
2231 * For headers read from a stream, this will affect {@link #rewriteable()}, so users should not call
2232 * this method unless they do not intend to {@link #rewrite()} this header into the original FITS.
2233 * </p>
2234 *
2235 * @see #ensureCardSpace(int)
2236 * @see #read(ArrayDataInput)
2237 * @see #getMinimumSize()
2238 * @see #rewriteable()
2239 * @see #rewrite()
2240 */
2241 @Deprecated
2242 public final void resetOriginalSize() {
2243 ensureCardSpace(1);
2244 }
2245
2246 @Override
2247 public void rewrite() throws FitsException, IOException {
2248 ArrayDataOutput dos = (ArrayDataOutput) input;
2249
2250 if (!rewriteable()) {
2251 throw new FitsException("Invalid attempt to rewrite Header.");
2252 }
2253
2254 FitsUtil.reposition(dos, fileOffset);
2255
2256 write(dos);
2257 dos.flush();
2258 }
2259
2260 @Override
2261 public boolean rewriteable() {
2262 long writeSize = FitsUtil
2263 .addPadding((long) Math.max(minCards, getNumberOfPhysicalCards()) * HeaderCard.FITS_HEADER_CARD_SIZE);
2264 return fileOffset >= 0 && input instanceof ArrayDataOutput && writeSize == getOriginalSize();
2265 }
2266
2267 /**
2268 * Set the BITPIX value for the header. The following values are permitted by FITS conventions:
2269 * <ul>
2270 * <li>8 -- signed byte data. Also used for tables.</li>
2271 * <li>16 -- signed short data.</li>
2272 * <li>32 -- signed int data.</li>
2273 * <li>64 -- signed long data.</li>
2274 * <li>-32 -- IEEE 32 bit floating point numbers.</li>
2275 * <li>-64 -- IEEE 64 bit floating point numbers.</li>
2276 * </ul>
2277 *
2278 * @deprecated Use the safer {@link #setBitpix(Bitpix)} instead.
2279 *
2280 * @param val The value set by the user.
2281 *
2282 * @throws IllegalArgumentException if the value is not a valid BITPIX value.
2283 *
2284 * @see #setBitpix(Bitpix)
2285 */
2286 @Deprecated
2287 public void setBitpix(int val) throws IllegalArgumentException {
2288 try {
2289 setBitpix(Bitpix.forValue(val));
2290 } catch (FitsException e) {
2291 throw new IllegalArgumentException("Invalid BITPIX value: " + val, e);
2292 }
2293 }
2294
2295 /**
2296 * Sets a standard BITPIX value for the header.
2297 *
2298 * @deprecated (<i>for internall use</i>) Visibility will be reduced to the package level in the future.
2299 *
2300 * @param bitpix The predefined enum value, e.g. {@link Bitpix#INTEGER}.
2301 *
2302 * @since 1.16
2303 *
2304 * @see #setBitpix(int)
2305 */
2306 @Deprecated
2307 public void setBitpix(Bitpix bitpix) {
2308 Cursor<String, HeaderCard> iter = iterator();
2309 iter.next();
2310 iter.add(bitpix.getHeaderCard());
2311 }
2312
2313 /**
2314 * Overwite the default header card sorter.
2315 *
2316 * @param headerSorter the sorter tu use or null to disable sorting
2317 */
2318 public void setHeaderSorter(Comparator<String> headerSorter) {
2319 this.headerSorter = headerSorter;
2320 }
2321
2322 /**
2323 * Set the value of the NAXIS keyword
2324 *
2325 * @deprecated (<i>for internal use</i>) Visibility will be reduced to the package level in the future.
2326 *
2327 * @param val The dimensionality of the data.
2328 */
2329 @Deprecated
2330 public void setNaxes(int val) {
2331 Cursor<String, HeaderCard> iter = iterator();
2332 iter.setKey(BITPIX.key());
2333 if (iter.hasNext()) {
2334 iter.next();
2335 }
2336 iter.add(HeaderCard.create(NAXIS, val));
2337 }
2338
2339 /**
2340 * Set the dimension for a given axis.
2341 *
2342 * @deprecated (<i>for internal use</i>) Visibility will be reduced to the package level in the future.
2343 *
2344 * @param axis The axis being set.
2345 * @param dim The dimension
2346 */
2347 @Deprecated
2348 public void setNaxis(int axis, int dim) {
2349 Cursor<String, HeaderCard> iter = iterator();
2350 if (axis <= 0) {
2351 LOG.warning("setNaxis ignored because axis less than 0");
2352 return;
2353 }
2354
2355 if (axis == 1) {
2356 iter.setKey(NAXIS.key());
2357 } else {
2358 iter.setKey(NAXISn.n(axis - 1).key());
2359 }
2360
2361 if (iter.hasNext()) {
2362 iter.next();
2363 }
2364 iter.add(HeaderCard.create(NAXISn.n(axis), dim));
2365 }
2366
2367 /**
2368 * Set the SIMPLE keyword to the given value.
2369 *
2370 * @deprecated (<i>for internall use</i>) Visibility will be reduced to the package level in the future.
2371 *
2372 * @param val <code>true</code> for the primary header, otherwise <code>false</code>
2373 */
2374 @Deprecated
2375 public void setSimple(boolean val) {
2376 deleteKey(SIMPLE);
2377 deleteKey(XTENSION);
2378 deleteKey(EXTEND);
2379
2380 Cursor<String, HeaderCard> iter = iterator();
2381
2382 iter.add(HeaderCard.create(SIMPLE, val));
2383
2384 // If we're flipping back to and from the primary header
2385 // we need to add in the EXTEND keyword whenever we become
2386 // a primary, because it's not permitted in the extensions
2387 // (at least not where it needs to be in the primary array).
2388 if (findCard(NAXIS) != null) {
2389 if (findCard(NAXISn.n(getIntValue(NAXIS))) != null) {
2390 iter.next();
2391 }
2392 }
2393
2394 iter.add(HeaderCard.create(EXTEND, true));
2395 }
2396
2397 /**
2398 * Set the XTENSION keyword to the given value.
2399 *
2400 * @deprecated (<i>for internall use</i>) Visibility will be reduced to the package level
2401 * in the future.
2402 *
2403 * @param val The name of the extension.
2404 *
2405 * @throws IllegalArgumentException if the string value contains characters that are not allowed in FITS
2406 * headers, that is characters outside of the 0x20 thru 0x7E range.
2407 */
2408 @Deprecated
2409 public void setXtension(String val) throws IllegalArgumentException {
2410 deleteKey(SIMPLE);
2411 deleteKey(XTENSION);
2412 deleteKey(EXTEND);
2413 iterator().add(HeaderCard.create(XTENSION, val));
2414 }
2415
2416 /**
2417 * @return the number of cards in the header
2418 *
2419 * @deprecated use {@link #getNumberOfCards()}. The units of the size of the header may be unclear.
2420 */
2421 @Deprecated
2422 public int size() {
2423 return cards.size();
2424 }
2425
2426 /**
2427 * Update a valued entry in the header, or adds a new header entry. If the header does not contain a prior entry for
2428 * the specific keyword, or if the keyword is a comment-style key, a new entry is added at the current editing
2429 * position. Otherwise, the matching existing entry is updated in situ.
2430 *
2431 * @param key The key of the card to be replaced (or added).
2432 * @param card A new card
2433 *
2434 * @throws HeaderCardException if the operation failed
2435 */
2436 public void updateLine(IFitsHeader key, HeaderCard card) throws HeaderCardException {
2437 updateLine(key.key(), card);
2438 }
2439
2440 private void updateValue(IFitsHeader key, Boolean value) {
2441 HeaderCard prior = cards.get(key.key());
2442 if (prior != null) {
2443 prior.setValue(value);
2444 } else {
2445 addValue(key, value);
2446 }
2447 }
2448
2449 private void updateValue(IFitsHeader key, Number value) {
2450 HeaderCard prior = cards.get(key.key());
2451 if (prior != null) {
2452 prior.setValue(value);
2453 } else {
2454 addValue(key, value);
2455 }
2456 }
2457
2458 private void updateValue(IFitsHeader key, String value) {
2459 HeaderCard prior = cards.get(key.key());
2460 if (prior != null) {
2461 prior.setValue(value);
2462 } else {
2463 addValue(key, value);
2464 }
2465 }
2466
2467 /**
2468 * Update an existing card in situ, without affecting the current position, or else add a new card at the current
2469 * position.
2470 *
2471 * @param key The key of the card to be replaced.
2472 * @param card A new card
2473 *
2474 * @throws HeaderCardException if the operation failed
2475 */
2476 public final void updateLine(String key, HeaderCard card) throws HeaderCardException {
2477 // Remove an existing card with the matching 'key' (even if that key
2478 // isn't the same
2479 // as the key of the card argument!)
2480 cards.update(key, card);
2481 }
2482
2483 /**
2484 * Overwrite the lines in the header. Add the new PHDU header to the current one. If keywords appear twice, the new
2485 * value and comment overwrite the current contents. By Richard J Mathar.
2486 *
2487 * @param newHdr the list of new header data lines to replace the current ones.
2488 *
2489 * @throws HeaderCardException if the operation failed
2490 *
2491 * @see #mergeDistinct(Header)
2492 */
2493 public void updateLines(final Header newHdr) throws HeaderCardException {
2494 Cursor<String, HeaderCard> j = newHdr.iterator();
2495
2496 while (j.hasNext()) {
2497 HeaderCard card = j.next();
2498 if (card.isCommentStyleCard()) {
2499 insertCommentStyle(card.getKey(), card.getComment());
2500 } else {
2501 updateLine(card.getKey(), card);
2502 }
2503 }
2504 }
2505
2506 /**
2507 * Writes a number of blank header records, for example to create preallocated blank header space as described by
2508 * the FITS 4.0 standard.
2509 *
2510 * @param dos the output stream to which the data is to be written.
2511 * @param n the number of blank records to add.
2512 *
2513 * @throws IOException if there was an error writing to the stream
2514 *
2515 * @since 1.16
2516 *
2517 * @see #ensureCardSpace(int)
2518 */
2519 private void writeBlankCards(ArrayDataOutput dos, int n) throws IOException {
2520 byte[] blank = new byte[HeaderCard.FITS_HEADER_CARD_SIZE];
2521 Arrays.fill(blank, (byte) ' ');
2522
2523 while (--n >= 0) {
2524 dos.write(blank);
2525 }
2526 }
2527
2528 /**
2529 * Add required keywords, and removes conflicting ones depending on whether it is designated as a primary header or
2530 * not.
2531 *
2532 * @param xType The value for the XTENSION keyword, or <code>null</code> if primary HDU.
2533 *
2534 * @throws FitsException if there was an error trying to edit the header.
2535 *
2536 * @since 1.17
2537 *
2538 * @see #validate(FitsOutput)
2539 */
2540 void setRequiredKeys(String xType) throws FitsException {
2541
2542 if (xType == null) {
2543 // Delete keys that cannot be in primary
2544 deleteKey(XTENSION);
2545
2546 // Some FITS readers don't like the PCOUNT and GCOUNT keywords in the primary header
2547 if (!getBooleanValue(GROUPS, false)) {
2548 deleteKey(PCOUNT);
2549 deleteKey(GCOUNT);
2550 }
2551
2552 // Make sure we have SIMPLE
2553 updateValue(SIMPLE, true);
2554 } else {
2555 // Delete keys that cannot be in extensions
2556 deleteKey(SIMPLE);
2557
2558 // Some FITS readers don't like the EXTEND keyword in extensions.
2559 deleteKey(EXTEND);
2560
2561 // Make sure we have XTENSION
2562 updateValue(XTENSION, xType);
2563 }
2564
2565 // Make sure we have BITPIX
2566 updateValue(BITPIX, getIntValue(BITPIX, Bitpix.VALUE_FOR_INT));
2567
2568 int naxes = getIntValue(NAXIS, 0);
2569 updateValue(NAXIS, naxes);
2570
2571 for (int i = 1; i <= naxes; i++) {
2572 IFitsHeader naxisi = NAXISn.n(i);
2573 updateValue(naxisi, getIntValue(naxisi, 1));
2574 }
2575
2576 if (xType == null) {
2577 updateValue(EXTEND, true);
2578 } else {
2579 updateValue(PCOUNT, getIntValue(PCOUNT, 0));
2580 updateValue(GCOUNT, getIntValue(GCOUNT, 1));
2581 }
2582 }
2583
2584 /**
2585 * Validates this header by making it a proper primary or extension header. In both cases it means adding required
2586 * keywords if missing, and removing conflicting cards. Then ordering is checked and corrected as necessary and
2587 * ensures that the <code>END</code> card is at the tail.
2588 *
2589 * @param asPrimary <code>true</code> if this header is to be a primary FITS header
2590 *
2591 * @throws FitsException If there was an issue getting the header into proper form.
2592 *
2593 * @since 1.17
2594 */
2595 public void validate(boolean asPrimary) throws FitsException {
2596 setRequiredKeys(asPrimary ? null : getStringValue(XTENSION, "UNKNOWN"));
2597 validate();
2598 }
2599
2600 /**
2601 * Validates the header making sure it has the required keywords and that the essential keywords appeat in the in
2602 * the required order
2603 *
2604 * @throws FitsException If there was an issue getting the header into proper form.
2605 */
2606 private void validate() throws FitsException {
2607 // Ensure that all cards are in the proper order.
2608 if (headerSorter != null) {
2609 cards.sort(headerSorter);
2610 }
2611
2612 checkBeginning();
2613 checkEnd();
2614
2615 updateChecksum();
2616 }
2617
2618 private void updateChecksum() throws FitsException {
2619 if (containsKey(Checksum.CHECKSUM)) {
2620 HeaderCard dsum = getCard(Checksum.DATASUM);
2621 if (dsum != null) {
2622 FitsCheckSum.setDatasum(this, dsum.getValue(Long.class, 0L));
2623 } else {
2624 deleteKey(Checksum.CHECKSUM);
2625 }
2626 }
2627 }
2628
2629 /**
2630 * (<i>for internal use</i>) Similar to {@link #write(ArrayDataOutput)}, but writes the header as is, without
2631 * ensuring that mandatory keys are present, and in the correct order, or that checksums are updated.
2632 *
2633 * @param out The output file or stream to which to write
2634 *
2635 * @throws FitsException if there was a violation of the FITS standard
2636 * @throws IOException if the output was not accessible
2637 *
2638 * @since 1.20.1
2639 *
2640 * @see #write(ArrayDataOutput)
2641 * @see #validate(boolean)
2642 */
2643 public void writeUnchecked(ArrayDataOutput out) throws FitsException, IOException {
2644 FitsSettings settings = FitsFactory.current();
2645 fileOffset = FitsUtil.findOffset(out);
2646
2647 Cursor<String, HeaderCard> writeIterator = cards.iterator(0);
2648
2649 int size = 0;
2650
2651 while (writeIterator.hasNext()) {
2652 HeaderCard card = writeIterator.next();
2653 byte[] b = AsciiFuncs.getBytes(card.toString(settings));
2654 size += b.length;
2655
2656 if (END.key().equals(card.getKey()) && minCards * HeaderCard.FITS_HEADER_CARD_SIZE > size) {
2657 // AK: Add preallocated blank header space before the END key.
2658 writeBlankCards(out, minCards - size / HeaderCard.FITS_HEADER_CARD_SIZE);
2659 size = minCards * HeaderCard.FITS_HEADER_CARD_SIZE;
2660 }
2661
2662 out.write(b);
2663 }
2664 FitsUtil.pad(out, size, (byte) ' ');
2665 out.flush();
2666 }
2667
2668 @Override
2669 public void write(ArrayDataOutput out) throws FitsException {
2670 validate();
2671
2672 try {
2673 writeUnchecked(out);
2674 } catch (IOException e) {
2675 throw new FitsException("IO Error writing header", e);
2676 }
2677 }
2678
2679 private void addDuplicate(HeaderCard dup) {
2680 // AK: Don't worry about duplicates for comment-style cards in general.
2681 if (dup.isCommentStyleCard()) {
2682 return;
2683 }
2684
2685 if (duplicates == null) {
2686 duplicates = new ArrayList<>();
2687 dupKeys = new HashSet<>();
2688 }
2689
2690 if (!dupKeys.contains(dup.getKey())) {
2691 HeaderCardParser.getLogger().log(Level.WARNING, "Multiple occurrences of key:" + dup.getKey());
2692 dupKeys.add(dup.getKey());
2693 }
2694
2695 duplicates.add(dup);
2696 }
2697
2698 /**
2699 * Check if the given key is the next one available in the header.
2700 */
2701 private void cardCheck(Cursor<String, HeaderCard> iter, IFitsHeader key) throws FitsException {
2702 cardCheck(iter, key.key());
2703 }
2704
2705 /**
2706 * Check if the given key is the next one available in the header.
2707 */
2708 private void cardCheck(Cursor<String, HeaderCard> iter, String key) throws FitsException {
2709 if (!iter.hasNext()) {
2710 throw new FitsException("Header terminates before " + key);
2711 }
2712 HeaderCard card = iter.next();
2713 if (!card.getKey().equals(key)) {
2714 throw new FitsException("Key " + key + " not found where expected. Found " + card.getKey());
2715 }
2716 }
2717
2718 private void checkFirstCard(String key) throws FitsException {
2719 // AK: key cannot be null by the caller already, so checking for it makes dead code.
2720 if (!SIMPLE.key().equals(key) && !XTENSION.key().equals(key)) {
2721 throw new FitsException("Not a proper FITS header: " + HeaderCard.sanitize(key) + " at " + fileOffset);
2722 }
2723 }
2724
2725 private void doCardChecks(Cursor<String, HeaderCard> iter, boolean isTable, boolean isExtension) throws FitsException {
2726 cardCheck(iter, BITPIX);
2727 cardCheck(iter, NAXIS);
2728 int nax = getIntValue(NAXIS);
2729
2730 for (int i = 1; i <= nax; i++) {
2731 cardCheck(iter, NAXISn.n(i));
2732 }
2733 if (isExtension) {
2734 cardCheck(iter, PCOUNT);
2735 cardCheck(iter, GCOUNT);
2736 if (isTable) {
2737 cardCheck(iter, TFIELDS);
2738 }
2739 }
2740 // This does not check for the EXTEND keyword which
2741 // if present in the primary array must immediately follow
2742 // the NAXISn.
2743 }
2744
2745 /**
2746 * Ensure that the header begins with a valid set of keywords. Note that we do not check the values of these
2747 * keywords.
2748 */
2749 private void checkBeginning() throws FitsException {
2750 Cursor<String, HeaderCard> iter = iterator();
2751 if (!iter.hasNext()) {
2752 throw new FitsException("Empty Header");
2753 }
2754 HeaderCard card = iter.next();
2755 String key = card.getKey();
2756 if (!key.equals(SIMPLE.key()) && !key.equals(XTENSION.key())) {
2757 throw new FitsException("No SIMPLE or XTENSION at beginning of Header");
2758 }
2759 boolean isTable = false;
2760 boolean isExtension = false;
2761 if (key.equals(XTENSION.key())) {
2762 String value = card.getValue();
2763 if (value == null || value.isEmpty()) {
2764 throw new FitsException("Empty XTENSION keyword");
2765 }
2766 isExtension = true;
2767 if (value.equals(XTENSION_BINTABLE) || value.equals("A3DTABLE") || value.equals("TABLE")) {
2768 isTable = true;
2769 }
2770 }
2771 doCardChecks(iter, isTable, isExtension);
2772
2773 Bitpix.fromHeader(this, false);
2774 }
2775
2776 /**
2777 * Ensure that the header has exactly one END keyword in the appropriate location.
2778 */
2779 private void checkEnd() {
2780 // Ensure we have an END card only at the end of the
2781 // header.
2782 Cursor<String, HeaderCard> iter = iterator();
2783
2784 HeaderCard card;
2785
2786 while (iter.hasNext()) {
2787 card = iter.next();
2788 if (!card.isKeyValuePair() && card.getKey().equals(END.key())) {
2789 iter.remove();
2790 }
2791 }
2792 // End cannot have a comment
2793 iter.add(HeaderCard.createCommentStyleCard(END.key(), null));
2794 }
2795
2796 /**
2797 * Is this a valid header.
2798 *
2799 * @return <CODE>true</CODE> for a valid header, <CODE>false</CODE> otherwise.
2800 */
2801 // TODO retire?
2802 private boolean isValidHeader() {
2803 if (getNumberOfCards() < MIN_NUMBER_OF_CARDS_FOR_VALID_HEADER) {
2804 return false;
2805 }
2806 Cursor<String, HeaderCard> iter = iterator();
2807 String key = iter.next().getKey();
2808 if (!key.equals(SIMPLE.key()) && !key.equals(XTENSION.key())) {
2809 return false;
2810 }
2811 key = iter.next().getKey();
2812 if (!key.equals(BITPIX.key())) {
2813 return false;
2814 }
2815 key = iter.next().getKey();
2816 if (!key.equals(NAXIS.key())) {
2817 return false;
2818 }
2819 while (iter.hasNext()) {
2820 key = iter.next().getKey();
2821 }
2822 return key.equals(END.key());
2823 }
2824
2825 /**
2826 * @deprecated Use {@link NullDataHDU} instead. Create a header for a null image.
2827 */
2828 @Deprecated
2829 void nullImage() {
2830 Cursor<String, HeaderCard> iter = iterator();
2831 iter.add(HeaderCard.create(SIMPLE, true));
2832 iter.add(Bitpix.BYTE.getHeaderCard());
2833 iter.add(HeaderCard.create(NAXIS, 0));
2834 iter.add(HeaderCard.create(EXTEND, true));
2835 }
2836
2837 /**
2838 * Find the end of a set of keywords describing a column or axis (or anything else terminated by an index). This
2839 * routine leaves the header ready to add keywords after any existing keywords with the index specified. The user
2840 * should specify a prefix to a keyword that is guaranteed to be present.
2841 */
2842 Cursor<String, HeaderCard> positionAfterIndex(IFitsHeader prefix, int col) {
2843 String colnum = String.valueOf(col);
2844 cursor().setKey(prefix.n(col).key());
2845 if (cursor().hasNext()) {
2846 // Bug fix (references to forward) here by Laurent Borges
2847 boolean toFar = false;
2848 while (cursor().hasNext()) {
2849 String key = cursor().next().getKey().trim();
2850 // AK: getKey() cannot return null so no need to check.
2851 if (key.length() <= colnum.length() || !key.substring(key.length() - colnum.length()).equals(colnum)) {
2852 toFar = true;
2853 break;
2854 }
2855 }
2856 if (toFar) {
2857 cursor().prev(); // Gone one too far, so skip back an element.
2858 }
2859 }
2860 return cursor();
2861 }
2862
2863 /**
2864 * Replace the key with a new key. Typically this is used when deleting or inserting columns. If the convention of
2865 * the new keyword is not compatible with the existing value a warning message is logged but no exception is thrown
2866 * (at this point).
2867 *
2868 * @param oldKey The old header keyword.
2869 * @param newKey the new header keyword.
2870 *
2871 * @return <CODE>true</CODE> if the card was replaced.
2872 *
2873 * @throws HeaderCardException If <CODE>newKey</CODE> is not a valid FITS keyword.
2874 */
2875 boolean replaceKey(IFitsHeader oldKey, IFitsHeader newKey) throws HeaderCardException {
2876
2877 if (oldKey.valueType() == VALUE.NONE) {
2878 throw new IllegalArgumentException("cannot replace comment-style " + oldKey.key());
2879 }
2880
2881 HeaderCard card = getCard(oldKey);
2882 VALUE newType = newKey.valueType();
2883
2884 if (card != null && oldKey.valueType() != newType && newType != VALUE.ANY) {
2885 Class<?> type = card.valueType();
2886 Exception e = null;
2887
2888 // Check that the exisating cards value is compatible with the expected type of the new key.
2889 if (newType == VALUE.NONE) {
2890 e = new IllegalArgumentException(
2891 "comment-style " + newKey.key() + " cannot replace valued key " + oldKey.key());
2892 } else if (Boolean.class.isAssignableFrom(type) && newType != VALUE.LOGICAL) {
2893 e = new IllegalArgumentException(newKey.key() + " cannot not support the existing boolean value.");
2894 } else if (String.class.isAssignableFrom(type) && newType != VALUE.STRING) {
2895 e = new IllegalArgumentException(newKey.key() + " cannot not support the existing string value.");
2896 } else if (ComplexValue.class.isAssignableFrom(type) && newType != VALUE.COMPLEX) {
2897 e = new IllegalArgumentException(newKey.key() + " cannot not support the existing complex value.");
2898 } else if (card.isDecimalType() && newType != VALUE.REAL && newType != VALUE.COMPLEX) {
2899 e = new IllegalArgumentException(newKey.key() + " cannot not support the existing decimal values.");
2900 } else if (Number.class.isAssignableFrom(type) && newType != VALUE.REAL && newType != VALUE.INTEGER
2901 && newType != VALUE.COMPLEX) {
2902 e = new IllegalArgumentException(newKey.key() + " cannot not support the existing numerical value.");
2903 }
2904
2905 if (e != null) {
2906 LOG.log(Level.WARNING, e.getMessage(), e);
2907 }
2908 }
2909
2910 return replaceKey(oldKey.key(), newKey.key());
2911 }
2912
2913 /**
2914 * Replace the key with a new key. Typically this is used when deleting or inserting columns so that TFORMx ->
2915 * TFORMx-1
2916 *
2917 * @param oldKey The old header keyword.
2918 * @param newKey the new header keyword.
2919 *
2920 * @return <CODE>true</CODE> if the card was replaced.
2921 *
2922 * @exception HeaderCardException If <CODE>newKey</CODE> is not a valid FITS keyword. TODO should be private
2923 */
2924 boolean replaceKey(String oldKey, String newKey) throws HeaderCardException {
2925 HeaderCard oldCard = getCard(oldKey);
2926 if (oldCard == null) {
2927 return false;
2928 }
2929 if (!cards.replaceKey(oldKey, newKey)) {
2930 throw new HeaderCardException("Duplicate key [" + newKey + "] in replace");
2931 }
2932 try {
2933 oldCard.changeKey(newKey);
2934 } catch (IllegalArgumentException e) {
2935 throw new HeaderCardException("New key [" + newKey + "] is invalid or too long for existing value.", e);
2936 }
2937 return true;
2938 }
2939
2940 /**
2941 * Calculate the unpadded size of the data segment from the header information.
2942 *
2943 * @return the unpadded data segment size.
2944 */
2945 private long trueDataSize() {
2946
2947 // AK: No need to be too strict here. We can get a data size even if the
2948 // header isn't 100% to spec,
2949 // as long as the necessary keys are present. So, just check for the
2950 // required keys, and no more...
2951 if (!containsKey(BITPIX.key()) || !containsKey(NAXIS.key())) {
2952 return 0L;
2953 }
2954
2955 int naxis = getIntValue(NAXIS, 0);
2956
2957 // If there are no axes then there is no data.
2958 if (naxis == 0) {
2959 return 0L;
2960 }
2961
2962 int[] axes = new int[naxis];
2963
2964 for (int axis = 1; axis <= naxis; axis++) {
2965 axes[axis - 1] = getIntValue(NAXISn.n(axis), 0);
2966 }
2967
2968 boolean isGroup = getBooleanValue(GROUPS, false);
2969
2970 int pcount = getIntValue(PCOUNT, 0);
2971 int gcount = getIntValue(GCOUNT, 1);
2972
2973 int startAxis = 0;
2974
2975 if (isGroup && naxis > 1 && axes[0] == 0) {
2976 startAxis = 1;
2977 }
2978
2979 long size = 1;
2980 for (int i = startAxis; i < naxis; i++) {
2981 size *= axes[i];
2982 }
2983
2984 size += pcount;
2985 size *= gcount;
2986
2987 // Now multiply by the number of bits per pixel and
2988 // convert to bytes.
2989 size *= Math.abs(getIntValue(BITPIX, 0)) / FitsIO.BITS_OF_1_BYTE;
2990
2991 return size;
2992 }
2993
2994 /**
2995 * <p>
2996 * Sets whether warnings about FITS standard violations are logged when a header is being read (parsed). Enabling
2997 * this feature can help identifying various standard violations in existing FITS headers, which nevertheless do not
2998 * prevent the successful reading of the header by this library.
2999 * </p>
3000 * <p>
3001 * If {@link FitsFactory#setAllowHeaderRepairs(boolean)} is set <code>false</code>, this will affect only minor
3002 * violations (e.g. a misplaced '=', missing space after '=', non-standard characters in header etc.), which
3003 * nevertheless do not interfere with the unamiguous parsing of the header information. More severe standard
3004 * violations, where some guessing may be required about the intent of some malformed header record, will throw
3005 * appropriate exceptions. If, however, {@link FitsFactory#setAllowHeaderRepairs(boolean)} is set <code>true</code>,
3006 * the parsing will throw fewer exceptions, and the additional issues may get logged as additional warning instead.
3007 *
3008 * @param value <code>true</code> if parser warnings about FITS standard violations when reading in existing FITS
3009 * headers are to be logged, otherwise <code>false</code>
3010 *
3011 * @see #isParserWarningsEnabled()
3012 * @see FitsFactory#setAllowHeaderRepairs(boolean)
3013 *
3014 * @since 1.16
3015 */
3016 public static void setParserWarningsEnabled(boolean value) {
3017 Level level = value ? Level.WARNING : Level.SEVERE;
3018 HeaderCardParser.getLogger().setLevel(level);
3019 Logger.getLogger(ComplexValue.class.getName()).setLevel(level);
3020 }
3021
3022 /**
3023 * Checks whether warnings about FITS standard violations are logged when a header is being read (parsed).
3024 *
3025 * @return <code>true</code> if parser warnings about FITS standard violations when reading in existing FITS headers
3026 * are enabled and logged, otherwise <code>false</code>
3027 *
3028 * @see #setParserWarningsEnabled(boolean)
3029 *
3030 * @since 1.16
3031 */
3032 public static boolean isParserWarningsEnabled() {
3033 return !HeaderCardParser.getLogger().getLevel().equals(Level.SEVERE);
3034 }
3035
3036 /**
3037 * Returns the current preferred alignment character position of inline header comments. This is the position at
3038 * which the '/' is placed for the inline comment. #deprecated
3039 *
3040 * @return The current alignment position for inline comments.
3041 *
3042 * @see #setCommentAlignPosition(int)
3043 *
3044 * @since 1.17
3045 */
3046 public static int getCommentAlignPosition() {
3047 return commentAlign;
3048 }
3049
3050 /**
3051 * Sets a new alignment position for inline header comments.
3052 *
3053 * @param pos [20:70] The character position to which inline comments should be aligned if
3054 * possible.
3055 *
3056 * @throws IllegalArgumentException if the position is outside of the allowed range.
3057 *
3058 * @see #getCommentAlignPosition()
3059 *
3060 * @deprecated Not recommended as it may violate the FITS standart for 'fixed-format'
3061 * header entries, and make our FITS files unreadable by software that
3062 * expects strict adherence to the standard. We will remove this feature in
3063 * the future.
3064 *
3065 * @since 1.17
3066 */
3067 @Deprecated
3068 public static void setCommentAlignPosition(int pos) throws IllegalArgumentException {
3069 if (pos < Header.MIN_COMMENT_ALIGN || pos > Header.MAX_COMMENT_ALIGN) {
3070 throw new IllegalArgumentException(
3071 "Comment alignment " + pos + " out of range (" + MIN_COMMENT_ALIGN + ":" + MAX_COMMENT_ALIGN + ").");
3072 }
3073 commentAlign = pos;
3074 }
3075 }