/*
 * some handy FITS (cfitsio) utilities to make life easier
 *
 */

#include <stdio.h>
#include "fitsio.h"

static int dryrun = 0;

/* 
 * fits_dryrun:
 */

void fits_dryrun(int d)
{
   dryrun = d;
}

/*
 * fits_error:
 *   print out cfitsio error messages and exit the program 
 *   this is basically the routine "printerror" from CFITSIO's  
 *   cookbook/speed test routines
 */

void fits_error( int status)     
{
  char status_str[FLEN_STATUS], errmsg[FLEN_ERRMSG];


  if (status==0) return;                  /* 0=ok, no need to do more checking */

  if (dryrun) {   /* actually, dryrun doesn't really work yet, for now, we will abort() */
    abort();      /* this should cause a coredump, which is nice for debuggers */
  }
  
  fits_get_errstatus(status, status_str);   /* get the error description */
  fprintf(stderr,"fits_error: status = %d: %s\n", status, status_str);


  if ( fits_read_errmsg(errmsg) ) {          /* get first message; null if stack is empty */
    fprintf(stderr,"Error message stack:\n");
    fprintf(stderr," %s\n", errmsg);
    while ( fits_read_errmsg(errmsg) )       /* get remaining messages */
      fprintf(stderr," %s\n", errmsg);
  }
  exit(status);       /* terminate the program, NEMO style, return error status to parent */
}


/* 
 *   LITTLE_ENDIAN:   return 1 if the machine is little endian, i.e. where the
 *                    bytes need to be swapped if meant for output to FITS
 */

int little_endian()
{
  short int n = 1;
  char *ep = (char *)&n;
 
  return (*ep != 0); /* Returns 1 on a little endian machine */
}


/* 
 *   BSWAP: swap bytes on some work level (normally 2,4,or 8)
 *
 *		dat	(in/out) pointer to the data
 *		len	(in) item length in bytes, this amount will be swapped
 *		cnt	(in) total number of data-items of length 'len' to be
 *			     swapped
 */

void bswap(void *vdat, int len, int cnt)
{
    char tmp, *dat = (char *) vdat;
    int k;

    if (len==1)
	return;
    else if (len==2)
        while (cnt--) {
            tmp = dat[0];  dat[0] = dat[1];  dat[1] = tmp;
            dat += 2;
        }
    else if (len==4)
        while (cnt--) {
            tmp = dat[0];  dat[0] = dat[3];  dat[3] = tmp;
            tmp = dat[1];  dat[1] = dat[2];  dat[2] = tmp;
            dat += 4;
        }
    else if (len==8)
        while (cnt--) {
            tmp = dat[0];  dat[0] = dat[7];  dat[7] = tmp;
            tmp = dat[1];  dat[1] = dat[6];  dat[6] = tmp;
            tmp = dat[2];  dat[2] = dat[5];  dat[5] = tmp;
            tmp = dat[3];  dat[3] = dat[4];  dat[4] = tmp;
            dat += 8;
        }
    else {  /* the general SLOOOOOOOOOWE case */
        for(k=0; k<len/2; k++) {
            tmp = dat[k];
            dat[k] = dat[len-1-k];
            dat[len-1-k] = tmp;
        }
    }
}
