about summary refs log tree commit diff
path: root/converter/other/fitstopnm.c
blob: 804d4ae92c625c8ce12c33bd8fce1414e9c4054c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
 /* fitstopnm.c - read a FITS file and produce a PNM.
 **
 ** Copyright (C) 1989 by Jef Poskanzer.
 **
 ** Permission to use, copy, modify, and distribute this software and its
 ** documentation for any purpose and without fee is hereby granted, provided
 ** that the above copyright notice appear in all copies and that both that
 ** copyright notice and this permission notice appear in supporting
 ** documentation.  This software is provided "as is" without express or
 ** implied warranty.
 **
 ** Hacked up version by Daniel Briggs  (dbriggs@nrao.edu)  20-Oct-92
 **
 ** Include floating point formats, more or less.  Will only work on
 ** machines that understand IEEE-754.  Added -scanmax -printmax
 ** -min -max and -noraw.  Ignore axes past 3, instead of error (many packages
 ** use pseudo axes).  Use a finite scale when max=min.  NB: Min and max
 ** are the real world FITS values (scaled), so watch out when bzer & bscale
 ** are not 0 & 1.  Datamin & datamax interpreted correctly in scaled case,
 ** and initialization changed to less likely values.  If datamin & max are
 ** not present in the header, the a first pass is made to determine them
 ** from the array values.
 **
 ** Modified by Alberto Accomazzi (alberto@cfa.harvard.edu), Dec 1, 1992.
 **
 ** Added understanding of 3-plane FITS files, the program is renamed
 ** fitstopnm.  Fixed some non-ansi declarations (DBL_MAX and FLT_MAX
 ** replace MAXDOUBLE and MAXFLOAT), fixed some scaling parameters to
 ** map the full FITS data resolution to the maximum PNM resolution,
 ** disabled min max scanning when reading from stdin.
 */

/*
  The official specification of FITS format (which is for more than
  just visual images) is at
  ftp://legacy.gsfc.nasa.gov/fits_info/fits_office/fits_standard.pdf

  An example FITS file is at

    http://fits.gsfc.nasa.gov/nrao_data/tests/incunabula/mndrll-8.fits

*/

#include <string.h>
#include <float.h>
#include <assert.h>
#include <stdbool.h>

#include "pm_config.h"
#include "pm_c_util.h"
#include "mallocvar.h"
#include "floatcode.h"
#include "shhopt.h"
#include "pnm.h"



struct CmdlineInfo {
    const char * inputFileName;
    unsigned int image;  /* zero if unspecified */
    float max;
    unsigned int maxSpec;
    float min;
    unsigned int minSpec;
    unsigned int scanmax;
    unsigned int printmax;
    unsigned int noraw;
        /* This is for backward compatibility only.  Use the common option
           -plain now.  (pnm_init() processes -plain).
        */
    unsigned int verbose;
    unsigned int omaxval;
    unsigned int omaxvalSpec;
};



static void
parseCommandLine(int argc, const char ** argv,
                 struct CmdlineInfo * const cmdlineP) {
/* --------------------------------------------------------------------------
   Parse program command line described in Unix standard form by argc
   and argv.  Return the information in the options as *cmdlineP.

   If command line is internally inconsistent (invalid options, etc.),
   issue error message to stderr and abort program.

   Note that the strings we return are stored in the storage that
   was passed to us as the argv array.  We also trash *argv.
--------------------------------------------------------------------------*/
    optEntry * option_def;
        /* Instructions to pm_optParseOptions3 on how to parse our options. */
    optStruct3 opt;

    unsigned int imageSpec;
    unsigned int option_def_index;

    MALLOCARRAY_NOFAIL(option_def, 100);

    option_def_index = 0;   /* incremented by OPTENT3 */
    OPTENT3(0, "image",    OPT_UINT,
            &cmdlineP->image,   &imageSpec,                            0);
    OPTENT3(0, "min",      OPT_FLOAT,
            &cmdlineP->min,     &cmdlineP->minSpec,                    0);
    OPTENT3(0, "max",      OPT_FLOAT,
            &cmdlineP->max,     &cmdlineP->maxSpec,                    0);
    OPTENT3(0, "scanmax",  OPT_FLAG,
            NULL,               &cmdlineP->scanmax,                    0);
    OPTENT3(0, "printmax", OPT_FLAG,
            NULL,               &cmdlineP->printmax,                   0);
    OPTENT3(0, "noraw",    OPT_FLAG,
            NULL,               &cmdlineP->noraw,                      0);
    OPTENT3(0, "verbose",  OPT_FLAG,
            NULL,               &cmdlineP->verbose,                    0);
    OPTENT3(0, "omaxval",  OPT_UINT,
            &cmdlineP->omaxval, &cmdlineP->omaxvalSpec,                0);

    opt.opt_table = option_def;
    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
    opt.allowNegNum = FALSE;   /* We have no parms that are negative numbers */

    /* Set some defaults the lazy way (using multiple setting of variables) */

    pm_optParseOptions3(&argc, (char**)argv, opt, sizeof(opt), 0);
        /* Uses and sets argc, argv, and some of *cmdlineP and others. */

    if (imageSpec) {
        if (cmdlineP->image == 0)
            pm_error("You may not specify zero for the image number.  "
                     "Images are numbered starting at 1.");
    } else
        cmdlineP->image = 0;

    if (cmdlineP->maxSpec && cmdlineP->minSpec) {
        if (cmdlineP->max <= cmdlineP->min)
            pm_error("-max must be greater than -min.  You specified "
                     "-max=%f, -min=%f", cmdlineP->max, cmdlineP->min);
    }

    if (argc-1 < 1)
        cmdlineP->inputFileName = "-";
    else {
        cmdlineP->inputFileName = argv[1];

        if (argc-1 > 1)
            pm_error("Too many arguments (%u).  The only non-option argument "
                     "is the input file name.", argc-1);
    }
    free(option_def);
}



typedef enum {
    VF_CHAR, VF_SHORT, VF_LONG, VF_FLOAT, VF_DOUBLE
} ValFmt;

struct FITS_Header {
    bool simple;      /* basic format */
    ValFmt valFmt;    /* format of values -- bits per pixel, integer/float */
    unsigned int naxis;  /* number of axes */
    unsigned int naxis1;       /* number of points on axis 1 */
    unsigned int naxis2;       /* number of points on axis 2 */
    unsigned int naxis3;       /* number of points on axis 3 */
    double datamin;   /* min # (Physical value!) */
    double datamax;   /* max #     "       "     */
    double bzer;      /* Physical value = Array value*bscale + bzero */
    double bscale;
};

struct FitsRasterInfo {
    ValFmt valFmt;
    double bzer;
    double bscale;
};

/* This code deals properly with integers, no matter what the byte order
   or integer size of the host machine.  We handle sign extension manually to
   prevent problems with signed/unsigned characters.  We read floating point
   values properly only when the host architecture conforms to IEEE-754.  If
   you need to tweak this code for other machines, you might want to get a
   copy of the FITS documentation from nssdca.gsfc.nasa.gov
*/

static void
readFitsChar(FILE *   const ifP,
             double * const vP) {

    /* 8 bit FITS integers are unsigned */

    int const ich = getc(ifP);

    if (ich == EOF)
        pm_error("EOF / read error");
    else
        *vP = ich;
}



static void
readFitsShort(FILE *   const ifP,
              double * const vP) {

    int ich;
    int ival;
    unsigned char c[8];

    ich = getc(ifP);

    if (ich == EOF)
        pm_error("EOF / read error");

    c[0] = ich;

    ich = getc(ifP);

    if (ich == EOF)
        pm_error("EOF / read error");

    c[1] = ich;

    if (c[0] & 0x80)
        ival = ~0xFFFF | c[0] << 8 | c[1];
    else
        ival = c[0] << 8 | c[1];

    *vP = ival;
}



static void
readFitsLong(FILE *   const ifP,
             double * const vP) {

    unsigned int i;
    long int lval;
    unsigned char c[4];

    for (i = 0; i < 4; ++i) {
        int const ich = getc(ifP);
        if (ich == EOF)
            pm_error("EOF / read error");
        c[i] = ich;
    }

    if (c[0] & 0x80)
        lval = ~0xFFFFFFFF | c[0] << 24 | c[1] << 16 | c[2] << 8 | c[3];
    else
        lval = c[0] << 24 | c[1] << 16 | c[2] << 8 | c[3] << 0;

    *vP = lval;
}



static void
readFitsFloat(FILE *   const ifP,
              double * const vP) {

    unsigned int i;
    pm_bigendFloat bigend;

    for (i = 0; i < 4; ++i) {
        int const ich = getc(ifP);
        if (ich == EOF)
            pm_error("EOF / read error");
        bigend.bytes[i] = ich;
    }

    *vP = pm_floatFromBigendFloat(bigend);
}



static void
readFitsDouble(FILE *   const ifP,
               double * const vP) {

    unsigned int i;
    pm_bigendDouble bigend;

    for (i = 0; i < 8; ++i) {
        int const ich = getc(ifP);
        if (ich == EOF)
            pm_error("EOF / read error");
        bigend.bytes[i] = ich;
    }

    *vP = pm_doubleFromBigendDouble(bigend);
}



static ValFmt
valFmtFromBitpix(int const bitpix) {
/*----------------------------------------------------------------------------
   Return the format of a "value" in the FITS file, given the value
   of the BITPIX header in the FITS file.

   BITPIX has a stupid format wherein it is fundamentally the number
   of bits per value, but its sign indicates whether it is integer
   or floating point.
-----------------------------------------------------------------------------*/
    switch (bitpix) {
    case  +8: return VF_CHAR;
    case +16: return VF_SHORT;
    case +32: return VF_LONG;
    case -32: return VF_FLOAT;
    case -64: return VF_DOUBLE;
    default:
        /* Every possibility is covered above. */
        assert(false);
        return 0;  /* quiet compiler warning */
    }
}



static void
readVal(FILE *   const ifP,
        ValFmt   const fmt,
        double * const vP) {

    switch (fmt) {
    case VF_CHAR:
        readFitsChar(ifP, vP);
        break;

    case VF_SHORT:
        readFitsShort(ifP, vP);
        break;

    case VF_LONG:
        readFitsLong(ifP, vP);
        break;

    case VF_FLOAT:
        readFitsFloat(ifP, vP);
        break;

    case VF_DOUBLE:
        readFitsDouble(ifP, vP);
        break;
    }
}



static void
readCard(FILE * const ifP,
         char * const buf) {

    size_t bytesRead;

    bytesRead = fread(buf, 1, 80, ifP);
    if (bytesRead < 80)
        pm_error("error reading header");
}




static void
processNaxisN(unsigned int   const n,
              int            const value,
              bool           const gotNaxis,
              unsigned int   const naxis,
              bool *         const gotNaxisNP,
              unsigned int * const naxisNP) {

    if (*gotNaxisNP)
        pm_error("Invalid FITS header: two NAXIS%u keywords", n);
    else {
        *gotNaxisNP = true;

        if (!gotNaxis)
            pm_error("Invalid FITS header: NAXIS must precede NAXIS%u", n);
        else if (naxis < n)
            pm_error("Invalid FITS header: NAXIS%u for image with "
                     "only %u axes", n, naxis);
        else if (value < 0)
            pm_error("Invalid NAXIS%u value %d in FITS header:  "
                     "Must not be negative", n, value);
        else
            *naxisNP = value;
    }
}



static void
readFitsHeader(FILE *               const ifP,
               struct FITS_Header * const hP) {


    bool gotEmpty, gotSimple, gotNaxis, gotN1, gotN2, gotN3, gotBitpix, gotEnd;

    gotEmpty  = false;  /* initial value */    
    gotSimple = false;  /* initial value */
    gotNaxis  = false;  /* initial value */
    gotN1     = false;  /* initial value */
    gotN2     = false;  /* initial value */
    gotN3     = false;  /* initial value */
    gotBitpix = false;  /* initial value */
    gotEnd    = false;  /* initial value */

    /* Set defaults */
    hP->bzer    = 0.0;
    hP->bscale  = 1.0;
    hP->datamin = - DBL_MAX;
    hP->datamax = DBL_MAX;

    while (!gotEnd) {
        unsigned int i;

        for (i = 0; i < 36; ++i) {
            char buf[81];
            char c;
            int n;

            readCard(ifP, buf); /* Reads into first 80 elements of buf[] */

            buf[80] = '\0'; /* Make ASCIIZ string */

            if (sscanf(buf, " %c", &c) < 1) {
                gotEmpty = true;
            } else if (sscanf(buf, "SIMPLE = %c", &c) == 1) {
                if (gotSimple)
                    pm_error("FITS header has two SIMPLE keywords");
                gotSimple = true;
                if (c == 'T' || c == 't')
                    hP->simple = true;
                else if (c == 'F' || c == 'f')
                    hP->simple = false;
                else
                    pm_error("Invalid SIMPLE value '%c'.  Only 'T' and 'F' "
                             "are recognized", c);
            } else if (sscanf(buf, "BITPIX = %d", &n) == 1) {
                if (gotBitpix)
                    pm_error("FITS header has two NAXIS keywords");
                gotBitpix = true;
                hP->valFmt = valFmtFromBitpix(n);
            } else if (sscanf(buf, "NAXIS = %d", &n) == 1) {
                gotNaxis = true;
                if (n < 0)
                    pm_error("Invalid value %d for NAXIS in FITS header.  "
                             "Value must not be negative", n);
                else
                    hP->naxis = n;
            } else if (sscanf(buf, "NAXIS1 = %d", &n) == 1) {
                processNaxisN(1, n, gotNaxis, hP->naxis, &gotN1, &hP->naxis1);
            } else if (sscanf(buf, "NAXIS2 = %d", &n) == 1) {
                processNaxisN(2, n, gotNaxis, hP->naxis, &gotN2, &hP->naxis2);
            } else if (sscanf(buf, "NAXIS3 = %d", &n) == 1) {
                processNaxisN(3, n, gotNaxis, hP->naxis, &gotN3, &hP->naxis3);
            } else if (sscanf(buf, "DATAMIN = %lf", &(hP->datamin)) == 1) {
            } else if (sscanf(buf, "DATAMAX = %lf", &(hP->datamax)) == 1) {
            } else if (sscanf(buf, "BZERO = %lf", &(hP->bzer)) == 1) {
            } else if (sscanf(buf, "BSCALE = %lf", &(hP->bscale)) == 1) {
            } else if (strncmp(buf, "END ", 4 ) == 0) {
                gotEnd = true;
                if (gotEmpty == true)
                    pm_message("Blank card(s) were encountered before "
			       "END in header");
            }
        }
    }
    if (!gotSimple)
        pm_error("FITS header missing the SIMPLE keyword");
    if (!gotBitpix)
        pm_error("FITS header missing the BITPIX keyword");
    if (!gotNaxis)
        pm_error("FITS header missing the NAXIS keyword");

    if (hP->naxis > 3)
        pm_error("FITS file has %u axes; this program can handle "
                 "no more than 3", hP->naxis);

    if (hP->naxis > 0 && !gotN1)
        pm_error("FITS header missing NAXIS1 keyword");
    if (hP->naxis > 1 && !gotN2)
        pm_error("FITS header missing NAXIS1 keyword");
    if (hP->naxis > 2 && !gotN3)
        pm_error("FITS header missing NAXIS3 keyword");
}



static void
interpretPlanes(struct FITS_Header const fitsHeader,
                unsigned int       const imageRequest,
                bool               const verbose,
                unsigned int *     const imageCountP,
                bool *             const multiplaneP,
                unsigned int *     const desiredImageP) {

    if (fitsHeader.naxis == 2) {
        *imageCountP   = 1;
        *multiplaneP   = FALSE;
        *desiredImageP = 1;
    } else {
        if (imageRequest) {
            if (imageRequest > fitsHeader.naxis3)
                pm_error("Only %u plane%s in this file.  "
                         "You requested image %u",
                         fitsHeader.naxis3, fitsHeader.naxis3 > 1 ? "s" : "",
                         imageRequest);
            else {
                *imageCountP   = fitsHeader.naxis3;
                *multiplaneP   = FALSE;
                *desiredImageP = imageRequest;
            }
        } else {
            if (fitsHeader.naxis3 == 3) {
                *imageCountP   = 1;
                *multiplaneP   = TRUE;
                *desiredImageP = 1;
            } else if (fitsHeader.naxis3 > 1)
                pm_error("This FITS file contains multiple (%u) images.  "
                         "You must specify which one you want with a "
                         "-image option.", fitsHeader.naxis3);
            else {
                *imageCountP   = fitsHeader.naxis3;
                *multiplaneP   = FALSE;
                *desiredImageP = 1;
            }
        }
    }
    if (verbose) {

        pm_message("FITS stream is %smultiplane", *multiplaneP ? "" : "not ");
        pm_message("We will take image %u (1 is first) of %u "
                   "in the FITS stream",
                   *desiredImageP, *imageCountP);
    }
}



static void
scanImageForMinMax(FILE *       const ifP,
                   unsigned int const images,
                   int          const cols,
                   int          const rows,
                   ValFmt       const valFmt,
                   double       const bscale,
                   double       const bzer,
                   unsigned int const imagenum,
                   bool         const multiplane,
                   double *     const dataminP,
                   double *     const datamaxP) {

    /* Note that a value in the file might be Not-A-Number.  We ignore
       such entries in computing the minimum and maximum for the image.
    */
    double dmax, dmin;
    unsigned int image;
    pm_filepos rasterPos;
    double fmaxval;

    pm_tell2(ifP, &rasterPos, sizeof(rasterPos));

    pm_message("Scanning file for scaling parameters");

    switch (valFmt) {
    case VF_CHAR:   fmaxval = 255.0;        break;
    case VF_SHORT:  fmaxval = 65535.0;      break;
    case VF_LONG:   fmaxval = 4294967295.0; break;
    case VF_FLOAT:  fmaxval = FLT_MAX;      break;
    case VF_DOUBLE: fmaxval = DBL_MAX;      break;
    }

    dmax = -fmaxval;
    dmin = fmaxval;
    for (image = 1; image <= images; ++image) {
        unsigned int row;
        for (row = 0; row < rows; ++row) {
            unsigned int col;
            for (col = 0; col < cols; ++col) {
                double val;
                readVal(ifP, valFmt, &val);
                if (image == imagenum || multiplane ) {
                    /* Note: if 'val' is NaN, result is 2nd operand */
                    dmax = MAX(val, dmax);
                    dmin = MIN(val, dmin);
                }
            }
        }
        if (bscale < 0.0) {
            double const origDmax = dmax;
            dmax = dmin;
            dmin = origDmax;
        }
    }
    *dataminP = dmin * bscale + bzer;
    *datamaxP = dmax * bscale + bzer;

    pm_message("Scan results: min=%f max=%f", *dataminP, *datamaxP);

    pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
}



static void
computeMinMax(FILE *             const ifP,
              unsigned int       const images,
              int                const cols,
              int                const rows,
              struct FITS_Header const h,
              unsigned int       const imagenum,
              bool               const multiplane,
              bool               const forcemin,
              bool               const forcemax,
              double             const frmin,
              double             const frmax,
              double *           const dataminP,
              double *           const datamaxP) {

    double datamin, datamax;

    datamin = -DBL_MAX;  /* initial assumption */
    datamax = DBL_MAX;   /* initial assumption */

    if (forcemin)
        datamin = frmin;
    if (forcemax)
        datamax = frmax;

    if (datamin == -DBL_MAX)
        datamin = h.datamin;
    if (datamax == DBL_MAX)
        datamax = h.datamax;

    if (datamin == -DBL_MAX || datamax == DBL_MAX) {
        double scannedDatamin, scannedDatamax;
        scanImageForMinMax(ifP, images, cols, rows,
                           h.valFmt, h.bscale, h.bzer,
                           imagenum, multiplane,
                           &scannedDatamin, &scannedDatamax);

        if (datamin == -DBL_MAX)
            datamin = scannedDatamin;
        if (datamax == DBL_MAX)
            datamax = scannedDatamax;
    }
    *dataminP = datamin;
    *datamaxP = datamax;
}



static xelval
determineMaxval(struct CmdlineInfo const cmdline,
                ValFmt             const valFmt,
                double             const datamax,
                double             const datamin) {

    xelval retval;

    if (cmdline.omaxvalSpec)
        retval = cmdline.omaxval;
    else {
        if (valFmt == VF_FLOAT || valFmt == VF_DOUBLE) {
            /* samples are floating point, which means the resolution
               could be anything.  So we just pick a convenient maxval
               of 255.  Before Netpbm 10.20 (January 2004), we did
               maxval = max - min for floating point as well as
               integer samples.
            */
            retval = 255;
            if (cmdline.verbose)
                pm_message("FITS image has floating point samples.  "
                           "Using maxval = %u.", (unsigned int)retval);
        } else {
            retval = MAX(1, MIN(PNM_OVERALLMAXVAL, datamax - datamin));
            if (cmdline.verbose)
                pm_message("FITS image has samples in the range %d-%d.  "
                           "Using maxval %u.",
                           (int)(datamin+0.5), (int)(datamax+0.5),
                           (unsigned int)retval);
        }
    }
    return retval;
}



static void
convertPgmRaster(FILE *                const ifP,
                 unsigned int          const cols,
                 unsigned int          const rows,
                 xelval                const maxval,
                 unsigned int          const desiredImage,
                 unsigned int          const imageCount,
                 struct FitsRasterInfo const rasterInfo,
                 double                const scale,
                 double                const datamin,
                 xel **                const xels) {

    /* Note: the FITS specification does not give the association between
       file position and image position (i.e. is the first pixel in the
       file the top left, bottom left, etc.).  We use the common sense,
       popular order of row major, top to bottom, left to right.  This
       has been the case and accepted since 1989, but in 2008, we discovered
       that Gimp and ImageMagick do bottom to top.
    */
    unsigned int image;

    pm_message("writing PGM file");

    for (image = 1; image <= desiredImage; ++image) {
        unsigned int row;
        if (image != desiredImage)
            pm_message("skipping image plane %u of %u", image, imageCount);
        else if (imageCount > 1)
            pm_message("reading image plane %u of %u", image, imageCount);
        for (row = 0; row < rows; ++row) {
            unsigned int col;
            for (col = 0; col < cols; ++col) {
                double val;
                readVal(ifP, rasterInfo.valFmt, &val);
                {
                    double const t = scale *
                        (val * rasterInfo.bscale + rasterInfo.bzer - datamin);
                    xelval const tx = MAX(0, MIN(t, maxval));
                    if (image == desiredImage)
                        PNM_ASSIGN1(xels[row][col], tx);
                }
            }
        }
    }
}



static void
convertPpmRaster(FILE *                const ifP,
                 unsigned int          const cols,
                 unsigned int          const rows,
                 xelval                const maxval,
                 struct FitsRasterInfo const rasterInfo,
                 double                const scale,
                 double                const datamin,
                 xel **                const xels) {
/*----------------------------------------------------------------------------
   Read the FITS raster from file *ifP into xels[][].  Image dimensions
   are 'cols' by 'rows'.  The FITS raster is 3 planes composing one
   image: a red plane followed by a green plane followed by a blue plane.
-----------------------------------------------------------------------------*/
    unsigned int plane;

    pm_message("Writing PPM file "
               "(Probably not what you want - consider an -image option)");

    for (plane = 0; plane < 3; ++plane) {
        unsigned int row;
        pm_message("reading image plane %u (%s)",
                   plane, plane == 0 ? "red" : plane == 1 ? "green" : "blue");
        for (row = 0; row < rows; ++row) {
            unsigned int col;
            for (col = 0; col < cols; ++col) {
                double val;
                readVal(ifP, rasterInfo.valFmt, &val);
                {
                    double const t = scale *
                        (val * rasterInfo.bscale + rasterInfo.bzer - datamin);
                    xelval const sample = MAX(0, MIN(t, maxval));

                    switch (plane) {
                    case 0: PPM_PUTR(xels[row][col], sample); break;
                    case 1: PPM_PUTG(xels[row][col], sample); break;
                    case 2: PPM_PUTB(xels[row][col], sample); break;
                    }
                }
            }
        }
    }
}



static void
convertRaster(FILE *                const ifP,
              unsigned int          const cols,
              unsigned int          const rows,
              xelval                const maxval,
              bool                  const forceplain,
              bool                  const multiplane,
              unsigned int          const desiredImage,
              unsigned int          const imageCount,
              struct FitsRasterInfo const rasterInfo,
              double                const scale,
              double                const datamin) {

    xel ** xels;
    int format;

    xels = pnm_allocarray(cols, rows);

    if (multiplane) {
        format = PPM_FORMAT;
        convertPpmRaster(ifP, cols, rows, maxval, rasterInfo, scale, datamin,
                         xels);
    } else {
        format = PGM_FORMAT;
        convertPgmRaster(ifP, cols, rows, maxval,
                         desiredImage, imageCount, rasterInfo, scale, datamin,
                         xels);
    }
    pnm_writepnm(stdout, xels, cols, rows, maxval, format, forceplain);
    pnm_freearray(xels, rows);
}



int
main(int argc, const char * argv[]) {

    struct CmdlineInfo cmdline;
    FILE * ifP;
    unsigned int cols, rows;
    xelval maxval;
    double scale;
    double datamin, datamax;
    struct FITS_Header fitsHeader;
    struct FitsRasterInfo rasterInfo;

    unsigned int imageCount;
    unsigned int desiredImage;
        /* Plane number (starting at one) of plane that contains the image
           we want.
        */
    bool multiplane;
        /* This is a one-image multiplane stream; 'desiredImage'
           is undefined
        */

    pm_proginit(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    ifP = pm_openr(cmdline.inputFileName);

    readFitsHeader(ifP, &fitsHeader);

    if (!fitsHeader.simple)
        pm_error("FITS file is not in simple format, can't read");

    if (fitsHeader.naxis != 2 && fitsHeader.naxis != 3)
        pm_message("Warning: FITS file has %u axes", fitsHeader.naxis);

    cols = fitsHeader.naxis1;
    rows = fitsHeader.naxis2;

    rasterInfo.bscale = fitsHeader.bscale;
    rasterInfo.bzer   = fitsHeader.bzer;
    rasterInfo.valFmt = fitsHeader.valFmt;

    interpretPlanes(fitsHeader, cmdline.image, cmdline.verbose,
                    &imageCount, &multiplane, &desiredImage);

    computeMinMax(ifP, imageCount, cols, rows, fitsHeader,
                  desiredImage, multiplane,
                  cmdline.minSpec, cmdline.maxSpec,
                  cmdline.min, cmdline.max,
                  &datamin, &datamax);

    maxval = determineMaxval(cmdline, rasterInfo.valFmt, datamax, datamin);

    if (datamax - datamin == 0)
        scale = 1.0;
    else
        scale = maxval / (datamax - datamin);

    if (cmdline.printmax)
        printf("%f %f\n", datamin, datamax);
    else
        convertRaster(ifP, cols, rows, maxval, cmdline.noraw,
                      multiplane, desiredImage, imageCount,
                      rasterInfo, scale, datamin);

    pm_close(ifP);
    pm_close(stdout);

    return 0;
}