/**************************************************************

konvoes.c (C-Munipack project)
Conversion functions for OES Astro files
Copyright (C) 2003 David Motl, dmotl@volny.cz

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

**************************************************************/

#include <stdlib.h>
#include <string.h>
#include <fitsio.h>

#include "imageheader.h"

/* Realloc procedure */
static void *realloc_proc(void *ptr, size_t len)
{
	return cmpack_realloc(ptr, len);
}

void cmpack_image_header_init(CmpackImageHeader *hdr)
{
	memset(hdr, 0, sizeof(CmpackImageHeader));
	ffimem((fitsfile**)&hdr->fits, (void**)&hdr->buffer, &hdr->bufsize, 0x4000, &realloc_proc, &hdr->status);
}

void cmpack_image_header_destroy(CmpackImageHeader *hdr)
{
	if (hdr->fits) {
		ffclos((fitsfile*)hdr->fits, &hdr->status);
		hdr->fits = NULL;
	}
	cmpack_free(hdr->buffer);
	hdr->buffer = NULL;
	hdr->bufsize = 0;
}

void cmpack_image_header_copy(const CmpackImageHeader *sfile, CmpackImageHeader *dfile)
{
	int i, status = 0, dstat = 0;
	char key[FLEN_KEYWORD], val[FLEN_VALUE], com[FLEN_COMMENT], card[FLEN_CARD];
	fitsfile *src = (fitsfile*)sfile->fits, *dst = (fitsfile*)dfile->fits;
	
	for (i=1; ffgkyn(src, i, key, val, com, &status)==0; i++) {
		/* Skip the following keywords: */
		if (key[0]=='\0' || strcmp(key, "SIMPLE")==0 || strcmp(key, "BITPIX")==0 ||
			strstr(key, "NAXIS")==key || strcmp(key, "EXTEND")==0 ||
			strcmp(key, "BZERO")==0 || strcmp(key, "BSCALE")==0 ||
			strcmp(key, "END")==0) 
				continue;
		/* Skip FITS default comments */
		if (strcmp(key, "COMMENT")==0 && (
			strstr(com, "FITS (Flexible Image Transport System) format is defined in 'Astronomy") ||
			strstr(com, "and Astrophysics', volume 376, page 359; bibcode: 2001A&A...376..359H")))
				continue;
		/* Copy card */
		if (ffgrec(src, i, card, &status)!=0)
			ffprec(dst, card, &dstat);
	}
}
