fits.c 31.5 KB
Newer Older
Elliot Lee's avatar
Elliot Lee committed
1
2
3
4
/* The GIMP -- an image manipulation program
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
 * FITS file plugin
 * reading and writing code Copyright (C) 1997 Peter Kirchgessner
5
 * e-mail: peter@kirchgessner.net, WWW: http://www.kirchgessner.net
Elliot Lee's avatar
Elliot Lee committed
6
7
8
9
10
11
12
13
14
15
16
17
18
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Elliot Lee's avatar
Elliot Lee committed
20
21
22
23
24
25
26
27
28
 *
 */

/* Event history:
 * V 1.00, PK, 05-May-97: Creation
 * V 1.01, PK, 19-May-97: Problem with compilation on Irix fixed
 * V 1.02, PK, 08-Jun-97: Bug with saving gray images fixed
 * V 1.03, PK, 05-Oct-97: Parse rc-file
 * V 1.04, PK, 12-Oct-97: No progress bars for non-interactive mode
29
 * V 1.05, nn, 20-Dec-97: Initialize image_ID in run()
30
31
32
 * V 1.06, PK, 21-Nov-99: Internationalization
 *                        Fix bug with gimp_export_image()
 *                        (moved it from load to save)
Elliot Lee's avatar
Elliot Lee committed
33
 */
34
static char ident[] = "@(#) GIMP FITS file-plugin v1.06  21-Nov-99";
Elliot Lee's avatar
Elliot Lee committed
35
36
37
38
39
40

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gtk/gtk.h"
#include "libgimp/gimp.h"
41
#include "libgimp/gimpui.h"
42
#include "libgimp/stdplugins-intl.h"
Elliot Lee's avatar
Elliot Lee committed
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
#include "fitsrw.h"

/* Load info */
typedef struct
{
  guint replace;    /* replacement for blank/NaN-values */
  guint use_datamin;/* Use DATAMIN/MAX-scaling if possible */
  guint compose;    /* compose images with naxis==3 */
} FITSLoadVals;

typedef struct
{
  gint run;
} FITSLoadInterface;

static FITSLoadVals plvals =
{
  0,        /* Replace with black */
  0,        /* Do autoscale on pixel-values */
  0         /* Dont compose images */
};

static FITSLoadInterface plint =
{
  FALSE
};


/* Declare some local functions.
 */
static void   init       (void);
static void   query      (void);
static void   run        (char    *name,
                          int      nparams,
                          GParam  *param,
                          int     *nreturn_vals,
                          GParam **return_vals);

static gint32 load_image (char *filename);
static gint   save_image (char *filename,
                          gint32  image_ID,
                          gint32  drawable_ID);

static FITS_HDU_LIST *create_fits_header (FITS_FILE *ofp,
                        guint width, guint height, guint bpp);
static gint save_index (FITS_FILE *ofp,
                        gint32 image_ID,
                        gint32 drawable_ID);
static gint save_direct(FITS_FILE *ofp,
                        gint32 image_ID,
                        gint32 drawable_ID);

static gint32 create_new_image (char *filename, guint pagenum,
                guint width, guint height,
                GImageType itype,
                GDrawableType dtype,
                gint32 *layer_ID, GDrawable **drawable,
                GPixelRgn *pixel_rgn);

static void   check_load_vals (void);

static gint32 load_fits (char *filename, FITS_FILE *ifp,
                         guint picnum, guint ncompose);


/* Dialog-handling */
#define LOAD_FITS_TOGGLES 3
typedef struct
{
  GtkWidget *dialog;
  int toggle_val[2*LOAD_FITS_TOGGLES];
} LoadDialogVals;

116
static void   init_gtk                 (void);
Elliot Lee's avatar
Elliot Lee committed
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

static gint   load_dialog              (void);
static void   load_close_callback      (GtkWidget *widget,
                                        gpointer   data);
static void   load_ok_callback         (GtkWidget *widget,
                                        gpointer   data);
static void   load_toggle_update       (GtkWidget *widget,
                                        gpointer   data);
static void   show_fits_errors         (void);
static void   show_message             (char *);


GPlugInInfo PLUG_IN_INFO =
{
  init,    /* init_proc */
  NULL,    /* quit_proc */
  query,   /* query_proc */
  run,     /* run_proc */
};


/* The run mode */
static GRunModeType l_run_mode;


MAIN ()


static void
init (void)

{
  gimp_set_data ("file_fits_load", &plvals, sizeof (FITSLoadVals));
}


static void
query (void)

{
  static GParamDef load_args[] =
  {
159
160
161
    { PARAM_INT32,    "run_mode",     "Interactive, non-interactive" },
    { PARAM_STRING,   "filename",     "The name of the file to load" },
    { PARAM_STRING,   "raw_filename", "The name of the file to load" },
Elliot Lee's avatar
Elliot Lee committed
162
163
164
  };
  static GParamDef load_return_vals[] =
  {
165
    { PARAM_IMAGE,    "image",        "Output image" },
Elliot Lee's avatar
Elliot Lee committed
166
167
168
169
170
171
172
  };
  static int nload_args = sizeof (load_args) / sizeof (load_args[0]);
  static int nload_return_vals = sizeof (load_return_vals)
                               / sizeof (load_return_vals[0]);

  static GParamDef save_args[] =
  {
173
174
175
176
177
    { PARAM_INT32,    "run_mode",     "Interactive, non-interactive" },
    { PARAM_IMAGE,    "image",        "Input image" },
    { PARAM_DRAWABLE, "drawable",     "Drawable to save" },
    { PARAM_STRING,   "filename",     "The name of the file to save the image in" },
    { PARAM_STRING,   "raw_filename", "The name of the file to save the image in" },
Elliot Lee's avatar
Elliot Lee committed
178
179
180
  };
  static int nsave_args = sizeof (save_args) / sizeof (save_args[0]);

181
182
  INIT_I18N();

Elliot Lee's avatar
Elliot Lee committed
183
  gimp_install_procedure ("file_fits_load",
184
185
186
                          _("load file of the FITS file format"),
                          _("load file of the FITS file format (Flexible Image\
 Transport System)"),
Elliot Lee's avatar
Elliot Lee committed
187
                          "Peter Kirchgessner",
188
                          "Peter Kirchgessner (peter@kirchgessner.net)",
Elliot Lee's avatar
Elliot Lee committed
189
190
191
192
193
194
195
196
                          "1997",
                          "<Load>/FITS",
                          NULL,
                          PROC_PLUG_IN,
                          nload_args, nload_return_vals,
                          load_args, load_return_vals);

  gimp_install_procedure ("file_fits_save",
197
198
199
                          _("save file in the FITS file format"),
                          _("FITS saving handles all image types except \
those with alpha channels."),
Elliot Lee's avatar
Elliot Lee committed
200
                          "Peter Kirchgessner",
201
                          "Peter Kirchgessner (peter@kirchgessner.net)",
Elliot Lee's avatar
Elliot Lee committed
202
203
                          "1997",
                          "<Save>/FITS",
204
                          "RGB, GRAY, INDEXED",
Elliot Lee's avatar
Elliot Lee committed
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
                          PROC_PLUG_IN,
                          nsave_args, 0,
                          save_args, NULL);

  /* Register file plugin by plugin name and handable extensions */
  gimp_register_magic_load_handler ("file_fits_load", "fit,fits", "",
                                    "0,string,SIMPLE");
  gimp_register_save_handler ("file_fits_save", "fit,fits", "");
}


static void
run (char    *name,
     int      nparams,
     GParam  *param,
     int     *nreturn_vals,
     GParam **return_vals)

{
  static GParam values[2];
  GRunModeType run_mode;
  GStatusType status = STATUS_SUCCESS;
  gint32 image_ID;
228
  gint32 drawable_ID;
Elliot Lee's avatar
Elliot Lee committed
229
230
231
232
233
234
235
236
237
238
239
240
241
242

  /* initialize */

  image_ID = -1;

  l_run_mode = run_mode = (GRunModeType)param[0].data.d_int32;

  *nreturn_vals = 1;
  *return_vals = values;
  values[0].type = PARAM_STATUS;
  values[0].data.d_status = STATUS_CALLING_ERROR;

  if (strcmp (name, "file_fits_load") == 0)
    {
243
244
      INIT_I18N_UI();

Elliot Lee's avatar
Elliot Lee committed
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
      *nreturn_vals = 2;
      values[1].type = PARAM_IMAGE;
      values[1].data.d_image = -1;

      switch (run_mode)
      {
        case RUN_INTERACTIVE:
          /*  Possibly retrieve data  */
          gimp_get_data ("file_fits_load", &plvals);

          if (!load_dialog ()) return;
          break;

        case RUN_NONINTERACTIVE:
          if (nparams != 3)
          {
            status = STATUS_CALLING_ERROR;
          }
          break;

        case RUN_WITH_LAST_VALS:
          /* Possibly retrieve data */
          gimp_get_data ("file_fits_load", &plvals);
          break;

        default:
          break;
      }
      if (status == STATUS_SUCCESS)
      {
        check_load_vals ();
        image_ID = load_image (param[1].data.d_string);

        /* Write out error messages of FITS-Library */
        show_fits_errors ();

        status = (image_ID != -1) ? STATUS_SUCCESS : STATUS_EXECUTION_ERROR;

        /*  Store plvals data  */
        if (status == STATUS_SUCCESS)
          gimp_set_data ("file_fits_load", &plvals, sizeof (FITSLoadVals));
      }
      values[0].data.d_status = status;
      values[1].data.d_image = image_ID;
    }
  else if (strcmp (name, "file_fits_save") == 0)
    {
292
293
294
295
      GimpExportReturnType export = EXPORT_CANCEL;

      INIT_I18N_UI();

296
297
298
299
      image_ID = param[1].data.d_int32;
      drawable_ID = param[2].data.d_int32;
      *nreturn_vals = 1;

300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
    /*  eventually export the image */
    switch (run_mode)
      {
      case RUN_INTERACTIVE:
      case RUN_WITH_LAST_VALS:
	init_gtk ();
	export = gimp_export_image (&image_ID, &drawable_ID, "FITS",
                  (CAN_HANDLE_RGB | CAN_HANDLE_GRAY | CAN_HANDLE_INDEXED));
	if (export == EXPORT_CANCEL)
	  {
	    *nreturn_vals = 1;
	    values[0].data.d_status = STATUS_EXECUTION_ERROR;
	    return;
	  }
	break;
      default:
	break;
      }

Elliot Lee's avatar
Elliot Lee committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
      switch (run_mode)
        {
        case RUN_INTERACTIVE:
          break;

        case RUN_NONINTERACTIVE:
          /*  Make sure all the arguments are there!  */
          if (nparams != 5)
            status = STATUS_CALLING_ERROR;
          break;

        case RUN_WITH_LAST_VALS:
          break;

        default:
          break;
        }

337
      if (save_image (param[3].data.d_string, image_ID, drawable_ID))
Elliot Lee's avatar
Elliot Lee committed
338
339
340
          values[0].data.d_status = STATUS_SUCCESS;
      else
        values[0].data.d_status = STATUS_EXECUTION_ERROR;
341
342
343

      if (export == EXPORT_EXPORT)
	gimp_image_delete (image_ID);
Elliot Lee's avatar
Elliot Lee committed
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
    }
}


static gint32
load_image (char *filename)

{gint32 image_ID, *image_list, *nl;
 guint picnum;
 int   k, n_images, max_images, hdu_picnum;
 int   compose;
 FILE *fp;
 FITS_FILE *ifp;
 FITS_HDU_LIST *hdu;

 fp = fopen (filename, "rb");
 if (!fp)
 {
362
   show_message (_("can't open file for reading"));
Elliot Lee's avatar
Elliot Lee committed
363
364
365
366
367
368
369
   return (-1);
 }
 fclose (fp);

 ifp = fits_open (filename, "r");
 if (ifp == NULL)
 {
370
   show_message (_("error during open of FITS file"));
Elliot Lee's avatar
Elliot Lee committed
371
372
373
374
   return (-1);
 }
 if (ifp->n_pic <= 0)
 {
375
   show_message (_("FITS file keeps no displayable images"));
Elliot Lee's avatar
Elliot Lee committed
376
377
378
379
380
381
382
   fits_close (ifp);
   return (-1);
 }

 image_list = (gint32 *)g_malloc (10 * sizeof (gint32));
 if (image_list == NULL)
 {
383
   show_message (_("out of memory"));
Elliot Lee's avatar
Elliot Lee committed
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
   return (-1);
 }
 n_images = 0;
 max_images = 10;

 for (picnum = 1; picnum <= ifp->n_pic; )
 {
   /* Get image info to see if we can compose them */
   hdu = fits_image_info (ifp, picnum, &hdu_picnum);
   if (hdu == NULL) break;

   /* Get number of FITS-images to compose */
   compose = (   plvals.compose && (hdu_picnum == 1) && (hdu->naxis == 3)
              && (hdu->naxisn[2] > 1) && (hdu->naxisn[2] <= 4));
   if (compose)
     compose = hdu->naxisn[2];
   else
     compose = 1;  /* Load as GRAY */

   image_ID = load_fits (filename, ifp, picnum, compose);

   /* Write out error messages of FITS-Library */
   show_fits_errors ();

   if (image_ID == -1) break;
   if (n_images == max_images)
   {
     nl = (gint32 *)g_realloc (image_list, (max_images+10)*sizeof (gint32));
     if (nl == NULL) break;
     image_list = nl;
     max_images += 10;
   }
   image_list[n_images++] = image_ID;

   picnum += compose;
 }

 /* Write out error messages of FITS-Library */
 show_fits_errors ();

 fits_close (ifp);

 /* Display images in reverse order. The last will be displayed by GIMP itself*/
 if (l_run_mode != RUN_NONINTERACTIVE)
 {
   for (k = n_images-1; k >= 1; k--)
   {
Marc Lehmann's avatar
Marc Lehmann committed
431
     gimp_image_undo_enable (image_list[k]);
Elliot Lee's avatar
Elliot Lee committed
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
     gimp_image_clean_all (image_list[k]);
     gimp_display_new (image_list[k]);
   }
 }

 image_ID = (n_images > 0) ? image_list[0] : -1;
 g_free (image_list);

 return (image_ID);
}


static gint
save_image (char *filename,
            gint32  image_ID,
            gint32  drawable_ID)

{
  FITS_FILE* ofp;
  GDrawableType drawable_type;
  gint retval;
  char *temp = ident; /* Just to satisfy lint/gcc */

  drawable_type = gimp_drawable_type (drawable_ID);

  /*  Make sure we're not saving an image with an alpha channel  */
  if (gimp_drawable_has_alpha (drawable_ID))
  {
460
    show_message (_("FITS save cannot handle images with alpha channels"));
Elliot Lee's avatar
Elliot Lee committed
461
462
463
464
465
466
467
468
469
470
    return FALSE;
  }

  switch (drawable_type)
  {
    case INDEXED_IMAGE: case INDEXEDA_IMAGE:
    case GRAY_IMAGE:    case GRAYA_IMAGE:
    case RGB_IMAGE:     case RGBA_IMAGE:
      break;
    default:
471
      show_message (_("cannot operate on unknown image types"));
Elliot Lee's avatar
Elliot Lee committed
472
473
474
475
476
477
478
479
      return (FALSE);
      break;
  }

  /* Open the output file. */
  ofp = fits_open (filename, "w");
  if (!ofp)
  {
480
    show_message (_("cant open file for writing"));
Elliot Lee's avatar
Elliot Lee committed
481
482
483
484
485
    return (FALSE);
  }

  if (l_run_mode != RUN_NONINTERACTIVE)
  {
486
487
    temp = g_malloc (strlen (filename) + 64);
    sprintf (temp, _("Saving %s:"), filename);
Elliot Lee's avatar
Elliot Lee committed
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
    gimp_progress_init (temp);
    g_free (temp);
  }

  if ((drawable_type == INDEXED_IMAGE) || (drawable_type == INDEXEDA_IMAGE))
    retval = save_index (ofp,image_ID, drawable_ID);
  else
    retval = save_direct (ofp,image_ID, drawable_ID);

  fits_close (ofp);

  return (retval);
}


/* Check (and correct) the load values plvals */
static void
check_load_vals (void)

{
  if (plvals.replace > 255) plvals.replace = 255;
}


/* Create an image. Sets layer_ID, drawable and rgn. Returns image_ID */
static gint32
create_new_image (char *filename,
                  guint pagenum,
                  guint width,
                  guint height,
                  GImageType itype,
                  GDrawableType dtype,
                  gint32 *layer_ID,
                  GDrawable **drawable,
                  GPixelRgn *pixel_rgn)

{gint32 image_ID;
 char *tmp;

 image_ID = gimp_image_new (width, height, itype);
528
 if ((tmp = g_malloc (strlen (filename) + 64)) != NULL)
Elliot Lee's avatar
Elliot Lee committed
529
530
531
532
533
534
535
536
 {
   sprintf (tmp, "%s-img%ld", filename, (long)pagenum);
   gimp_image_set_filename (image_ID, tmp);
   g_free (tmp);
 }
 else
   gimp_image_set_filename (image_ID, filename);

537
 *layer_ID = gimp_layer_new (image_ID, _("Background"), width, height,
Elliot Lee's avatar
Elliot Lee committed
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
                             dtype, 100, NORMAL_MODE);
 gimp_image_add_layer (image_ID, *layer_ID, 0);

 *drawable = gimp_drawable_get (*layer_ID);
 gimp_pixel_rgn_init (pixel_rgn, *drawable, 0, 0, (*drawable)->width,
                      (*drawable)->height, TRUE, FALSE);

 return (image_ID);
}


/* Load FITS image. ncompose gives the number of FITS-images which have */
/* to be composed together. This will result in different GIMP image types: */
/* 1: GRAY, 2: GRAYA, 3: RGB, 4: RGBA */
static gint32
load_fits (char *filename,
           FITS_FILE *ifp,
           guint picnum,
           guint ncompose)

{register unsigned char *dest, *src;
 unsigned char *data, *data_end, *linebuf;
 int width, height, tile_height, scan_lines;
 int i, j, channel, max_scan;
 double a, b;
 gint32 layer_ID, image_ID;
 GPixelRgn pixel_rgn;
 GDrawable *drawable;
 GImageType itype;
 GDrawableType dtype;
 int err = 0;
 FITS_HDU_LIST *hdulist;
 FITS_PIX_TRANSFORM trans;

 hdulist = fits_seek_image (ifp, (int)picnum);
 if (hdulist == NULL) return (-1);

 width = hdulist->naxisn[0];  /* Set the size of the FITS image */
 height = hdulist->naxisn[1];

 if (ncompose == 2) { itype = GRAY; dtype = GRAYA_IMAGE; }
 else if (ncompose == 3) { itype = RGB; dtype = RGB_IMAGE; }
 else if (ncompose == 4) { itype = RGB; dtype = RGBA_IMAGE; }
 else { ncompose = 1; itype = GRAY; dtype = GRAY_IMAGE;}

 image_ID = create_new_image (filename, picnum, width, height, itype, dtype,
                              &layer_ID, &drawable, &pixel_rgn);

 tile_height = gimp_tile_height ();
 data = g_malloc (tile_height * width * ncompose);
 if (data == NULL) return (-1);
 data_end = data + tile_height * width * ncompose;

 /* If the transformation from pixel value to */
 /* data value has been specified, use it */
 if (   plvals.use_datamin
     && hdulist->used.datamin && hdulist->used.datamax
     && hdulist->used.bzero && hdulist->used.bscale)
 {
   a = (hdulist->datamin - hdulist->bzero) / hdulist->bscale;
   b = (hdulist->datamax - hdulist->bzero) / hdulist->bscale;
   if (a < b) trans.pixmin = a, trans.pixmax = b;
   else trans.pixmin = b, trans.pixmax = a;
 }
 else
 {
   trans.pixmin = hdulist->pixmin;
   trans.pixmax = hdulist->pixmax;
 }
 trans.datamin = 0.0;
 trans.datamax = 255.0;
 trans.replacement = plvals.replace;
 trans.dsttyp = 'c';

 /* FITS stores images with bottom row first. Therefore we have */
 /* to fill the image from bottom to top. */

 if (ncompose == 1)
 {
   dest = data + tile_height * width;
   scan_lines = 0;

   for (i = 0; i < height; i++)
   {
     /* Read FITS line */
     dest -= width;
     if (fits_read_pixel (ifp, hdulist, width, &trans, dest) != width)
     {
       err = 1;
       break;
     }

     scan_lines++;

     if ((l_run_mode != RUN_NONINTERACTIVE) && ((i % 20) == 0))
       gimp_progress_update ((double)(i+1) / (double)height);

     if ((scan_lines == tile_height) || ((i+1) == height))
     {
       gimp_pixel_rgn_set_rect (&pixel_rgn, dest, 0, height-i-1,
                                width, scan_lines);
       scan_lines = 0;
       dest = data + tile_height * width;
     }
     if (err) break;
   }
 }
 else   /* multiple images to compose */
 {
   linebuf = g_malloc (width);
   if (linebuf == NULL) return (-1);

   for (channel = 0; channel < ncompose; channel++)
   {
     dest = data + tile_height * width * ncompose + channel;
     scan_lines = 0;

     for (i = 0; i < height; i++)
     {
       if ((channel > 0) && ((i % tile_height) == 0))
       { /* Reload a region for follow up channels */
         max_scan = tile_height;
         if (i + tile_height > height) max_scan = height - i;
         gimp_pixel_rgn_get_rect (&pixel_rgn, data_end-max_scan*width*ncompose,
                                  0, height-i-max_scan, width, max_scan);
       }

       /* Read FITS scanline */
       dest -= width*ncompose;
       if (fits_read_pixel (ifp, hdulist, width, &trans, linebuf) != width)
       {
         err = 1;
         break;
       }
       j = width;
       src = linebuf;
       while (j--)
       {
         *dest = *(src++);
         dest += ncompose;
       }
       dest -= width*ncompose;
       scan_lines++;

       if ((l_run_mode != RUN_NONINTERACTIVE) && ((i % 20) == 0))
         gimp_progress_update (  (double)(channel*height+i+1)
                               / (double)(height*ncompose));

       if ((scan_lines == tile_height) || ((i+1) == height))
       {
         gimp_pixel_rgn_set_rect (&pixel_rgn, dest-channel, 0, height-i-1,
                                  width, scan_lines);
         scan_lines = 0;
         dest = data + tile_height * width * ncompose + channel;
       }
       if (err) break;
     }
   }
   g_free (linebuf);
 }

 g_free (data);

 if (err)
702
   show_message (_("EOF encountered on reading"));
Elliot Lee's avatar
Elliot Lee committed
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

 gimp_drawable_flush (drawable);

 return (err ? -1 : image_ID);
}


static FITS_HDU_LIST *
create_fits_header (FITS_FILE *ofp,
                   guint width,
                   guint height,
                   guint bpp)

{FITS_HDU_LIST *hdulist;
 int print_ctype3 = 0;   /* The CTYPE3-card may not be FITS-conforming */
 static char *ctype3_card[] = {
   NULL, NULL, NULL,  /* bpp = 0: no additional card */
   "COMMENT Image type within GIMP: GRAY_IMAGE",
   NULL,
   NULL,
   "COMMENT Image type within GIMP: GRAYA_IMAGE (gray with alpha channel)",
   "COMMENT Sequence for NAXIS3   : GRAY, ALPHA",
   "CTYPE3  = 'GRAYA   '           / GRAY IMAGE WITH ALPHA CHANNEL",
   "COMMENT Image type within GIMP: RGB_IMAGE",
   "COMMENT Sequence for NAXIS3   : RED, GREEN, BLUE",
   "CTYPE3  = 'RGB     '           / RGB IMAGE",
   "COMMENT Image type within GIMP: RGBA_IMAGE (rgb with alpha channel)",
   "COMMENT Sequence for NAXIS3   : RED, GREEN, BLUE, ALPHA",
   "CTYPE3  = 'RGBA    '           / RGB IMAGE WITH ALPHA CHANNEL"
 };

 hdulist = fits_add_hdu (ofp);
 if (hdulist == NULL) return (NULL);

 hdulist->used.simple = 1;
 hdulist->bitpix = 8;
 hdulist->naxis = (bpp == 1) ? 2 : 3;
 hdulist->naxisn[0] = width;
 hdulist->naxisn[1] = height;
 hdulist->naxisn[2] = bpp;
 hdulist->used.datamin = 1;
 hdulist->datamin = 0.0;
 hdulist->used.datamax = 1;
 hdulist->datamax = 255.0;
 hdulist->used.bzero = 1;
 hdulist->bzero = 0.0;
 hdulist->used.bscale = 1;
 hdulist->bscale = 1.0;

 fits_add_card (hdulist, "");
 fits_add_card (hdulist,
  "HISTORY THIS FITS FILE WAS GENERATED BY GIMP USING FITSRW");
 fits_add_card (hdulist, "");
 fits_add_card (hdulist,
757
  "COMMENT FitsRW is (C) Peter Kirchgessner (peter@kirchgessner.net), but available");
Elliot Lee's avatar
Elliot Lee committed
758
759
760
 fits_add_card (hdulist,
  "COMMENT under the GNU general public licence."),
 fits_add_card (hdulist,
761
  "COMMENT For sources see http://www.kirchgessner.net");
Elliot Lee's avatar
Elliot Lee committed
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
 fits_add_card (hdulist, "");
 fits_add_card (hdulist, ctype3_card[bpp*3]);
 if (ctype3_card[bpp*3+1] != NULL)
   fits_add_card (hdulist, ctype3_card[bpp*3+1]);
 if (print_ctype3 && (ctype3_card[bpp*3+2] != NULL))
   fits_add_card (hdulist, ctype3_card[bpp*3+2]);
 fits_add_card (hdulist, "");

 return (hdulist);
}


/* Save direct colours (GRAY, GRAYA, RGB, RGBA) */
static gint
save_direct  (FITS_FILE *ofp,
              gint32 image_ID,
              gint32 drawable_ID)

{ int height, width, i, j, channel;
  int tile_height, bpp, bpsl;
  long nbytes;
  unsigned char *data, *src;
  GPixelRgn pixel_rgn;
  GDrawable *drawable;
  GDrawableType drawable_type;
  FITS_HDU_LIST *hdu;

  drawable = gimp_drawable_get (drawable_ID);
  drawable_type = gimp_drawable_type (drawable_ID);
  width = drawable->width;
  height = drawable->height;
  bpp = drawable->bpp;       /* Bytes per pixel */
  bpsl = width * bpp;        /* Bytes per scanline */
  tile_height = gimp_tile_height ();
  gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, width, height, FALSE, FALSE);

  /* allocate a buffer for retrieving information from the pixel region  */
  src = data = (unsigned char *)g_malloc (width * height * bpp);

  hdu = create_fits_header (ofp, width, height, bpp);
  if (hdu == NULL) return (FALSE);
  if (fits_write_header (ofp, hdu) < 0) return (FALSE);

#define GET_DIRECT_TILE(begin) \
  {int scan_lines; \
    scan_lines = (i+tile_height-1 < height) ? tile_height : (height-i); \
    gimp_pixel_rgn_get_rect (&pixel_rgn, begin, 0, height-i-scan_lines, \
    width, scan_lines); \
    src = begin+bpsl*(scan_lines-1)+channel; }

  nbytes = 0;
  for (channel = 0; channel < bpp; channel++)
  {
    for (i = 0; i < height; i++)
    {
      if ((i % tile_height) == 0) GET_DIRECT_TILE (data); /* get more data */

      if (bpp == 1)  /* One channel only ? Write the scanline */
      {
        fwrite (src, 1, width, ofp->fp);
        src += bpsl;
      }
      else           /* Multiple channels */
      {
        for (j = 0; j < width; j++)  /* Write out bytes for current channel */
        {
          putc (*src, ofp->fp);
          src += bpp;
        }
      }
      nbytes += bpsl;
      src -= 2*bpsl;

      if ((l_run_mode != RUN_NONINTERACTIVE) && ((i % 20) == 0))
        gimp_progress_update ((double)(i+channel*height)/(double)(height*bpp));
    }
  }

  nbytes = nbytes % FITS_RECORD_SIZE;
  if (nbytes)
  {
    while (nbytes++ < FITS_RECORD_SIZE)
      putc (0, ofp->fp);
  }

  g_free (data);

  gimp_drawable_detach (drawable);

  if (ferror (ofp->fp))
  {
853
    show_message (_("write error occured"));
Elliot Lee's avatar
Elliot Lee committed
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
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
    return (FALSE);
  }
  return (TRUE);
#undef GET_DIRECT_TILE
}


/* Save indexed colours (INDEXED, INDEXEDA) */
static gint
save_index (FITS_FILE *ofp,
            gint32 image_ID,
            gint32 drawable_ID)

{ int height, width, i, j, channel;
  int tile_height, bpp, bpsl, ncols;
  long nbytes;
  unsigned char *data, *src, *cmap, *cmapptr;
  unsigned char red[256], green[256], blue[256];
  unsigned char *channels[3];
  GPixelRgn pixel_rgn;
  GDrawable *drawable;
  GDrawableType drawable_type;
  FITS_HDU_LIST *hdu;

  channels[0] = red;   channels[1] = green;   channels[2] = blue;

  drawable = gimp_drawable_get (drawable_ID);
  drawable_type = gimp_drawable_type (drawable_ID);
  width = drawable->width;
  height = drawable->height;
  bpp = drawable->bpp;       /* Bytes per pixel */
  bpsl = width * bpp;        /* Bytes per scanline */
  tile_height = gimp_tile_height ();
  gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, width, height, FALSE, FALSE);

  /* allocate a buffer for retrieving information from the pixel region  */
  src = data = (unsigned char *)g_malloc (width * height * bpp);

  cmapptr = cmap = gimp_image_get_cmap (image_ID, &ncols);
  if (ncols > sizeof (red)) ncols = sizeof (red);
  for (i = 0; i < ncols; i++)
  {
    red[i] = *(cmapptr++);
    green[i] = *(cmapptr++);
    blue[i] = *(cmapptr++);
  }
  for (i = ncols; i < sizeof (red); i++)
    red[i] = green[i] = blue[i] = 0;

  hdu = create_fits_header (ofp, width, height, bpp+2);
  if (hdu == NULL) return (FALSE);
  if (fits_write_header (ofp, hdu) < 0) return (FALSE);

#define GET_INDEXED_TILE(begin) \
  {int scan_lines; \
    scan_lines = (i+tile_height-1 < height) ? tile_height : (height-i); \
    gimp_pixel_rgn_get_rect (&pixel_rgn, begin, 0, height-i-scan_lines, \
                             width, scan_lines); \
    src = begin+bpsl*(scan_lines-1); }

  nbytes = 0;

  /* Write the RGB-channels */
  for (channel = 0; channel < 3; channel++)
  {
    cmapptr = channels[channel];
    for (i = 0; i < height; i++)
    {
      if ((i % tile_height) == 0) GET_INDEXED_TILE (data); /* get more data */

      for (j = 0; j < width; j++)  /* Write out bytes for current channel */
      {
        putc (cmapptr[*src], ofp->fp);
        src += bpp;
      }
      nbytes += width;
      src -= 2*bpsl;
    }

    if ((l_run_mode != RUN_NONINTERACTIVE) && ((i % 20) == 0))
      gimp_progress_update ((double)(i+channel*height)/(double)(height*(bpp+2)));
  }

  /* Write the Alpha-channel */
  if (bpp > 1)
  {
    for (i = 0; i < height; i++)
    {
      if ((i % tile_height) == 0)
      {
        GET_INDEXED_TILE (data); /* get more data */
        src++;                   /* Step to alpha channel data */
      }

      for (j = 0; j < width; j++)  /* Write out bytes for alpha channel */
      {
        putc (*src, ofp->fp);
        src += bpp;
      }
      nbytes += width;
      src -= 2*bpsl;
    }

    if ((l_run_mode != RUN_NONINTERACTIVE) && ((i % 20) == 0))
      gimp_progress_update ((double)(i+channel*height)/(double)(height*(bpp+2)));
  }

  nbytes = nbytes % FITS_RECORD_SIZE;
  if (nbytes)
  {
    while (nbytes++ < FITS_RECORD_SIZE)
      putc (0, ofp->fp);
  }

  g_free (data);

  gimp_drawable_detach (drawable);

  if (ferror (ofp->fp))
  {
974
    show_message (_("write error occured"));
Elliot Lee's avatar
Elliot Lee committed
975
976
977
978
979
980
981
    return (FALSE);
  }
  return (TRUE);
#undef GET_INDEXED_TILE
}


982
static void
983
984
985
986
987
988
989
990
init_gtk ()
{
  gchar **argv;
  gint argc;

  argc = 1;
  argv = g_new (gchar *, 1);
  argv[0] = g_strdup ("fits");
991

992
993
994
995
996
  gtk_init (&argc, &argv);
  gtk_rc_parse (gimp_gtkrc ());
}


Elliot Lee's avatar
Elliot Lee committed
997
998
999
1000
1001
1002
1003
/*  Load interface functions  */

static gint
load_dialog (void)

{
  LoadDialogVals *vals;
Sven Neumann's avatar
Sven Neumann committed
1004
  GtkWidget *hbbox;
Elliot Lee's avatar
Elliot Lee committed
1005
1006
1007
1008
1009
  GtkWidget *button;
  GtkWidget *toggle;
  GtkWidget *frame;
  GtkWidget *toggle_vbox;
  GSList *group;
1010
  gint k, j;
Elliot Lee's avatar
Elliot Lee committed
1011
1012
  char **textptr;
  static char *toggle_text[] = {
1013
1014
1015
    N_("BLANK/NaN pixel replacement"), N_("Black"), N_("White"),
    N_("Pixel value scaling"), N_("Automatic"), N_("by DATAMIN/DATAMAX"),
    N_("Image composing"), N_("None"), "NAXIS=3, NAXIS3=2,...,4"
Elliot Lee's avatar
Elliot Lee committed
1016
1017
  };

1018
  init_gtk ();
Elliot Lee's avatar
Elliot Lee committed
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029

  vals = g_malloc (sizeof (*vals));

  vals->toggle_val[0] = (plvals.replace == 0);
  vals->toggle_val[1] = !(vals->toggle_val[0]);
  vals->toggle_val[2] = (plvals.use_datamin == 0);
  vals->toggle_val[3] = !(vals->toggle_val[2]);
  vals->toggle_val[4] = (plvals.compose == 0);
  vals->toggle_val[5] = !(vals->toggle_val[4]);

  vals->dialog = gtk_dialog_new ();
1030
  gtk_window_set_title (GTK_WINDOW (vals->dialog), _("Load FITS File"));
Elliot Lee's avatar
Elliot Lee committed
1031
1032
1033
1034
1035
1036
  gtk_window_position (GTK_WINDOW (vals->dialog), GTK_WIN_POS_MOUSE);
  gtk_signal_connect (GTK_OBJECT (vals->dialog), "destroy",
                      (GtkSignalFunc) load_close_callback,
                      NULL);

  /*  Action area  */
Sven Neumann's avatar
Sven Neumann committed
1037
1038
1039
1040
1041
1042
1043
  gtk_container_set_border_width (GTK_CONTAINER (GTK_DIALOG (vals->dialog)->action_area), 2);
  gtk_box_set_homogeneous (GTK_BOX (GTK_DIALOG (vals->dialog)->action_area), FALSE);
  hbbox = gtk_hbutton_box_new ();
  gtk_button_box_set_spacing (GTK_BUTTON_BOX (hbbox), 4);
  gtk_box_pack_end (GTK_BOX (GTK_DIALOG (vals->dialog)->action_area), hbbox, FALSE, FALSE, 0);
  gtk_widget_show (hbbox);
 
1044
  button = gtk_button_new_with_label (_("OK"));
Elliot Lee's avatar
Elliot Lee committed
1045
1046
  GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
  gtk_signal_connect (GTK_OBJECT (button), "clicked",
Sven Neumann's avatar
Sven Neumann committed
1047
1048
1049
		      (GtkSignalFunc) load_ok_callback,
		      vals);
  gtk_box_pack_start (GTK_BOX (hbbox), button, FALSE, FALSE, 0);
Elliot Lee's avatar
Elliot Lee committed
1050
1051
1052
  gtk_widget_grab_default (button);
  gtk_widget_show (button);

1053
  button = gtk_button_new_with_label (_("Cancel"));
Elliot Lee's avatar
Elliot Lee committed
1054
1055
  GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
  gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
Sven Neumann's avatar
Sven Neumann committed
1056
1057
1058
			     (GtkSignalFunc) gtk_widget_destroy,
			     GTK_OBJECT (vals->dialog));
  gtk_box_pack_start (GTK_BOX (hbbox), button, FALSE, FALSE, 0);
Elliot Lee's avatar
Elliot Lee committed
1059
1060
1061
1062
1063
  gtk_widget_show (button);

  textptr = toggle_text;
  for (k = 0; k < LOAD_FITS_TOGGLES; k++)
  {
1064
1065
    frame = gtk_frame_new (gettext (*textptr));
    textptr++;
Elliot Lee's avatar
Elliot Lee committed
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
    gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_ETCHED_IN);
    gtk_container_border_width (GTK_CONTAINER (frame), 10);
    gtk_box_pack_start (GTK_BOX (GTK_DIALOG (vals->dialog)->vbox),
                        frame, FALSE, TRUE, 0);
    toggle_vbox = gtk_vbox_new (FALSE, 5);
    gtk_container_border_width (GTK_CONTAINER (toggle_vbox), 5);
    gtk_container_add (GTK_CONTAINER (frame), toggle_vbox);

    group = NULL;
    for (j = 0; j < 2; j++)
    {
1077
1078
      toggle = gtk_radio_button_new_with_label (group, gettext (*textptr));
      textptr++;
Elliot Lee's avatar
Elliot Lee committed
1079
1080
1081
1082
1083
      group = gtk_radio_button_group (GTK_RADIO_BUTTON (toggle));
      gtk_box_pack_start (GTK_BOX (toggle_vbox), toggle, FALSE, FALSE, 0);
      gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
                          (GtkSignalFunc) load_toggle_update,
                          &(vals->toggle_val[k*2+j]));
1084
1085
      gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle),
				    vals->toggle_val[k*2+j]);
Elliot Lee's avatar
Elliot Lee committed
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
      gtk_widget_show (toggle);
    }
    gtk_widget_show (toggle_vbox);
    gtk_widget_show (frame);
  }

  gtk_widget_show (vals->dialog);

  gtk_main ();
  gdk_flush ();

  g_free (vals);

  return plint.run;
}


static void
load_close_callback (GtkWidget *widget,
                     gpointer   data)

{
  gtk_main_quit ();
}


static void
load_ok_callback (GtkWidget *widget,
                  gpointer   data)

{LoadDialogVals *vals = (LoadDialogVals *)data;

  /* Read replacement */
  plvals.replace = (vals->toggle_val[0]) ? 0 : 255;

  /* Read pixel value scaling */
  plvals.use_datamin = vals->toggle_val[3];

  /* Read image composing */
  plvals.compose = vals->toggle_val[5];

  plint.run = TRUE;
  gtk_widget_destroy (GTK_WIDGET (vals->dialog));
}


static void
load_toggle_update (GtkWidget *widget,
                    gpointer   data)

{
  int *toggle_val;

  toggle_val = (int *) data;

  if (GTK_TOGGLE_BUTTON (widget)->active)
    *toggle_val = 1;
  else
    *toggle_val = 0;
}


static void show_fits_errors (void)

{
  char *msg;

  /* Write out error messages of FITS-Library */
  while ((msg = fits_get_error ()) != NULL)
    show_message (msg);
}


/* Show a message. Where to show it, depends on the runmode */
static void show_message (char *message)

{
 if (l_run_mode == RUN_INTERACTIVE)
1164
   gimp_message (message);
Elliot Lee's avatar
Elliot Lee committed
1165
1166
1167
 else
   fprintf (stderr, "Fits: %s\n", message);
}