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


/*	
	prints out a fits file in ASCII format to standout output

		PFITS fname [BOX=] [WIDTH=] [help]


	9/22/92 - usage and exit(0) -rrt
	10/27/92- added labels for row and col numbers.  MWR
	8/4/93 - reduce the default width from 8-->5 rrt
	1/7/96  - added 'help' option.  MWR
*/

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

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

char *usage = "usage: pfits fname [box=] [width=] [help]";

int
main(argc, argv)
int argc;
char *argv[];
{
	int i, boxno, row, figs = 5;
	int nrow, ncol, sr = 0, sc = 0, nr, nc;
	FITS_HANDLE fh;
	FILE *fout;
	static int16 data[NMAX];
	char format[NBUF], format2[NBUF], bar[NBUF], *gotit;

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

	fh = fits_open(argv[1], "r", &nrow, &ncol);
	nr = nrow;	
	nc = ncol;

	fout = stdout;

	for (i = 2; i < argc; i++) {
		if (keyword("help", argv[i])) {
			printf("%s\n", usage);
			exit(0);
		}
		if ((gotit = find("box", argv[i])) != NULL) {
			boxno = (int) evaluate(gotit);
			if (getbox(boxno, &sr, &sc, &nr, &nc))
				error(-1, "box not found");
			check_box(boxno, nrow, ncol);
			continue;
		}
		if ((gotit = find("width", argv[i])) != NULL) {
			figs = (int) (evaluate(gotit) + SMALL);
			continue;
		}
		sprintf(format, "unknown switch '%s'\n", argv[i]);
		error(-1, format);
	}
	sprintf(format, "%%%dd", figs);

	/* the labels for cols, along the top of the list */
	sprintf(format2, "%%%ds", figs); 
	fprintf(fout, format2, " ");
	for (i = sc; i < sc + nc; i++) {
		fprintf(fout, format, i);
	}
	fprintf(fout, "\n");
	for (i = 0; i < figs; i++)
		bar[i] = '-';
	bar[i] = '\0';
	fprintf(fout, format2, " ");
	for (i = 0; i < nc; i++)
		fprintf(fout, format2, bar);
	fprintf(fout, "\n");
	
	sprintf(format2, "%%-%dd|", figs - 1);
	for (row = sr; row < (sr + nr); row++) {

		/* label for row number, along left edge of list */
		fprintf(fout, format2, row);

		fits_get_data(fh, row, sc, data, nc);
		for (i = 0; i < nc; i++)
			fprintf(fout, format, data[i]);
		if (!fprintf(fout, "\n"))
			error(-1, "write error");
	}
	fclose(fout);

	exit(0);
}
	
	
