
	/* routines used to add/subtract/skip a pseudo-FITS header 
	   at the beginning of an otherwise normal-ASCII data file */

/*
 * 1/2/2001 -- replaced NULL with EOF in test in fits_file_type().
 *             MWR
 *
 */

#include <stdio.h>
#include <ctype.h>
#include "pf.h"
#include "header.h"

int skip_header( /* FILE *fp */ );
int fits_file_type( /* char *filename */ );
int is_a_fits_line( /* char *line */ );
void die( /* char *s */ );

static char err_msg[BIG_BUF];

	/* given a FILE pointer, move it ahead until it points to the first
	   line after the first END line in the pseudo-FITS header.  return
	   0 if all is OK, or 1 if there is a problem.  In the latter case,
	   the position of the file pointer is UNDEFINED! */

int
skip_header(fp)
FILE *fp;
{
	char line[BIG_BUF + 1];

	rewind(fp);
	while (fgets(line, BIG_BUF, fp) != NULL) {
		if (strncmp(line, "END", 3) == 0)
			break;
	}
	if (strncmp(line, "END", 3) == 0)
		return(0);
	else
		return(1);
}

	/* return TRUE_FITS if the file is true FITS, or PSEUDO_FITS 
	   if it is pseudo-FITS, or NOT_FITS if it is neither.  The 
	   checks I make are pretty simple, so they may be wrong
	   sometimes.... */

int
fits_file_type(filename)
char *filename;
{
	int i;
	char line[FITS_LINELEN + 2];
	FILE *fp;

	if ((fp = fopen(filename, "r")) == NULL) {
		sprintf(err_msg, "can't open file %s", filename);
		die(err_msg);
	}

	line[FITS_LINELEN + 1] = '\0';
	for (i = 0; i < FITS_LINELEN + 1; i++) {
		if ((line[i] = fgetc(fp)) == EOF)
			die("end of file in first line?!");
		if (line[i] == '\n')
			break;
	}
	if (line[i] == '\n') {			/* can't be true FITS */
		if (is_a_fits_line(line))
			return(PSEUDO_FITS);
		else
			return(NOT_FITS);
	}
	else {
		if (is_a_fits_line(line))
			return(TRUE_FITS);
		else
			return(NOT_FITS);
	}

	/* should never get here */
}

	/* return 1 if the given line has a format that looks like a FITS
	   header line (i.e. an 8-char name, an equals sign, then some sort
	   of value -- or COMMENT), or 0 if it doesn't. */

int
is_a_fits_line(line)
char *line;
{
	int i;
	
	if (strncmp(line, "COMMENT", 7) == 0)
		return(1);
	if (strncmp(line, "END", 3) == 0)
		return(1);
/***	ADDED BY RRT  **/
	if( line[0] == '#' )
		return 1;
/*************************/
	for (i = 0; i < 8; i++)
		if ((!isalnum(line[i])) && (line[i] != ' '))
			return(0);
	if (line[8] != '=')
		return(0);
	for (i = 9; i < strlen(line); i++) {
		if (line[i] == '\n')
			return(1);
		if (!isprint(line[i]))
			return(0);
	}

	return(1);
}

	/* print an error message and exit with code 1 */

void
die(s)
char *s;
{
	fprintf(stderr, "%s\n", s);
	exit(1);
}

