
/**************************************************************************
 *                                                                        *
 * 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.                        *
 *                                                                        *
 **************************************************************************/


/*	
	converts image files of the following format to FITS format,
	given the number of rows and cols in the image.

	   (ncol*nrow) bytes - 16-bit data values for each pixel

	usage:

		CONVERT filename nrow ncol [outname] [shift]

	9/22/92 - exit(0) added
*/

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

#ifdef PROTO
int main(int, char **);
static void symbols(FITS_HANDLE, int);
#else
int static symbols();
#endif

#define USAGE "usage: convert filename nrow ncol [outname] [shift] [help]"

int
main(argc, argv)
int argc;
char *argv[];
{
	FILE *fin;
	FITS_HANDLE fout;
	static int i, nrow, ncol, row, shift_flag, done;
	static int16 data[NMAX];
	char outname[NBUF];

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

	if ((fin = fopen(argv[1], "rb")) == NULL)
		error(-1, "can't open input file");	
	strcpy(outname, argv[1]);
	sscanf(argv[2], "%d", &nrow);
	sscanf(argv[3], "%d", &ncol);

	for (i = 4; i < argc; i++) {
		if (keyword("help", argv[i])) {
			printf("%s\n", USAGE);
			exit(0);
		}
		if (keyword("shift", argv[i])) {
			shift_flag = 1;
			continue;
		}
		if (done){
			char buf[NBUF];
			sprintf(buf,"convert: unknown option '%s'",argv[i]);
			error(-1, buf);
		}
		strcpy(outname, argv[i]);
		done = 1;
	}		
	fout = fits_open(outname, "w", &nrow, &ncol);

	/* seek to the beginning of the data */
	fseek(fin, (long) 0, 0);

	for (row = 0; row < nrow; row++) {
		if (fread(data, 2, ncol, fin) != ncol)
			error(-1, "read error");
		if (shift_flag)
			for (i = 0; i < ncol; i++)
				data[i] = data[i] >> 1;
		fits_put_data(fout, row, 0, data, ncol);
	}
	symbols(fout, shift_flag);
	fits_close(fout);

	exit(0);
}
		


static void 
symbols(fout, shift_flag)
FITS_HANDLE fout;
int shift_flag;
{
	char buf[NBUF];
	double scale;

	if(shift_flag)
		scale = 2.0;
	else
		scale = 1.0;
	sprintf(buf,"%20.6E", scale);
	fits_put_symbol(fout, "BSCALE", buf);

	sprintf(buf, "%20.6E", 1.0);
	fits_put_symbol(fout, "CDELT1", buf);
	fits_put_symbol(fout, "CDELT2", buf);

	sprintf(buf, "%20.6E", 0.0);
	fits_put_symbol(fout, "CRVAL1", buf);
	fits_put_symbol(fout, "CRVAL2", buf);

}

	
