/**************************************************************************
 *                                                                        *
 * Copyright (c) 1996 Michael Richmond and Richard Treffers               *
 *                                                                        *
 *                    This software may be copied and distributed for     *
 *                    educational, research and not for profit services   *
 *                    provided that this copyright and statement are      *
 *                    included in all such copies.                        *
 *                                                                        *
 **************************************************************************/


/*
 * Swaps the bytes in the data section of a FITS image.
 */


#include "pcvista.h"
#include "fits.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>



#ifdef PROTO
int main(int, char **);
#endif

#define USAGE "usage: swapbyte file [outfile=] [help]"


int
main(argc,argv)
int argc;
char *argv[];
{
	FITS_HANDLE fh, fout;
	static int i;
	static int nr, nc, sr, sc, nrow, ncol, row;
	static int16 data[NMAX], swapped[NMAX];
        uint16 hibyte, lowbyte;
	char *gotit, outfile[NBUF];
	int new_file = 0;

	if (argc == 1) {
		fprintf(stderr, "%s\n", USAGE);
		exit(1);
	}
	if (strcmp(argv[1], "help") == 0) {
		printf("%s\n", USAGE);
		exit(0);
	}

	fh = fits_open(argv[1], "r", &nrow, &ncol);
	strcpy(outfile,argv[1]);
	nr = nrow;
	nc = ncol;	
	sr = 0;
	sc = 0;

	for (i = 2; i < argc; i++) {
		if (keyword("help", argv[i])) {
			printf("%s\n", USAGE);
			exit(0);
		}
		if ((gotit = find("outfile", argv[i])) != NULL) {
			strcpy(outfile, gotit);
			new_file = 1;
			continue;
		}
	}

	fout = fits_open(outfile, new_file?"w":"x", &nrow, &ncol);

	if (new_file) {
		fits_copyheader(fh, fout, FITS_CHECK);
	}
			
	for (row = sr; row < (sr+nr); row++) {

		/* read data from the input file */
		fits_get_data(fh, row, sc, data, nc);

		/* swap the bytes, and place into the "swapped" array */
		for (i = 0; i < nc ; i++) {
			lowbyte = ((uint16) data[i]) & 0x00FF;
			hibyte = ((uint16) data[i]) & 0xFF00;
#ifdef DEBUG
printf("  data %6d  low %6d  high %6d \n", data[i], lowbyte, hibyte);
#endif
			lowbyte <<= 8;
			hibyte >>= 8;
			swapped[i] = lowbyte | hibyte;
#ifdef DEBUG
printf("            low %6d  high %6d   new %6d \n", lowbyte, hibyte, swapped[i]);
#endif
		}

		/* write to the output file */
		fits_put_data(fout, row, sc, swapped, nc);
	}

	fits_close(fout);
	exit(0);
}
