/****************************************************************************/
/*                                                                          */
/*  fits2pgm.c                                                              */
/*                                                                          */
/*  PURPOSE:    Convert FITS file to RAW file.                              */
/*                                                                          */
/****************************************************************************/
/*
** Copyright (C) 1998 Chris Albertson <chrisja@jps.net>
**  
** 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 
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/


/* Used by RCS and ident */
char fits2pgm_rcsid[] = 
    "$Id:$";


#include <stdio.h>
#include <string.h>
#include <errno.h>
/*#include <stdlib.h>*/

#include "fitsio.h" 
#include "pgm.h"

/* Prototypes */
void CheckFitsError(int status, char file[], int line);
int FITS2IA(void);

static float   *IA;
static int      nx, ny;
static char    fitsfilename[256];

   
int main(int argc, char *argv[])
{
    int i;
    double          p_min;
    double          p_max;
    double          range;
    double          scale;
    unsigned char   out_pix;
 
    if(argc != 2)
    {
        fprintf(stderr,"Usage fits2raw <fitsfilename>\n");
        exit(1);
    }
    strncpy(fitsfilename, argv[1], sizeof(fitsfilename));
    
    FITS2IA();
    /* fprintf(stderr, "%d x %d\n", nx, ny); */
    
    /* Find range of data array */ 
    p_max = p_min = IA[1]; 
    for(i=0; i<(nx*ny); i++)
    {
        if(p_max < IA[i]) p_max = IA[i];
        if(p_min > IA[i]) p_min = IA[i];
    }
    range = p_max - p_min;
    
    
    scale = 255.0/range;
    for(i=0; i<(nx*ny); i++)
    {
        out_pix = 0.5 + ((IA[i]-p_min) * scale);
        putc(out_pix, stdout);
    }
     
    exit(0);   
}

int FITS2IA(void)
{
    fitsfile   *fptr;
    int         fpixel;
    int         npixels;
    int         status;
    int         anynul;
    
    int         f_res;
    int         simple;
    int         bitpix;
    int         naxis;
    long        naxes[3];
    long        pcount;
    long        gcount;
    int         extend;
    int         ccd;

    
    /****************************************************************/
    /* Open the file                                                */
    /****************************************************************/
    status = 0;
    f_res = fits_open_file(&fptr, fitsfilename, READONLY, &status);
    if(f_res)
    {
        CheckFitsError(status, __FILE__, __LINE__);
        return -1;
    }
    
    /****************************************************************/
    /* Read a few keywords to check if this is n aceptable file     */
    /****************************************************************/
    fprintf(stderr, "reading keywords\n");
    status = 0;
    f_res = fits_read_imghdr(fptr, 2, 
            &simple, &bitpix, &naxis, naxes, &pcount, &gcount, &extend,
            &status);
            
    nx = naxes[0];
    ny = naxes[1];
    
    if(f_res)
    {
        CheckFitsError(status, __FILE__, __LINE__);
        return -1;
    }
        
    /****************************************************************/
    /* Watch carful folks!   We must first get some memory in which */
    /* to store the image data.  We will only read the file once.   */
    /* if there are more CCDs than one in the system we do a binary */
    /* copy later.  But we always allocate memory for _all_ CCDs    */
    /* at this time.                                                */
    /****************************************************************/
    IA = calloc(4, (naxes[0]*naxes[1]) );
    if(!IA)
    {
        /* Out of menory */
        fprintf(stderr, "INTERNAL ERROR: out of memory.  can not read RAM Buffer.\n");
        fprintf(stderr, "    detected in %s:%d\n", __FILE__, __LINE__);
        return -1;
    }
    
    /****************************************************************/
    /* Now read in the image array                                  */
    /****************************************************************/
    fprintf(stderr, "reading fits image\n");
    fpixel  = 1;
    npixels = naxes[0] * naxes[1];
    anynul  = 0;
    status  = 0;
    f_res = fits_read_img(fptr, TFLOAT, fpixel, npixels, NULL, IA,
            &anynul, &status);
    if(f_res)
    {
        CheckFitsError(status, __FILE__, __LINE__);
        return -1;
    }
    
    
    /****************************************************************/
    /* close the file                                               */
    /****************************************************************/
    f_res = fits_close_file(fptr, &status);
    if(f_res)
    {
        CheckFitsError(status, __FILE__, __LINE__);
        return -1;
    }
    
    return 0;
}


void CheckFitsError(int status, char file[], int line)
{
    char    err_text[256];
    int     more;
    
    
    if(status)
    {
        fits_get_errstatus(status, err_text);
        fprintf(stderr,"ERROR: %d -- %s\n", status, err_text);
         
        more = fits_read_errmsg(err_text);  
        while(more)
        {
            fprintf(stderr,"       %s\n", err_text);
            more = fits_read_errmsg(err_text);
        }
        fprintf(stderr,"       detected in %s:%d\n", file, line);
    }
    return;
}

