#include <stdio.h>
#include "pslib.h"
#include "papmodule.h"

static bool writePixels(psFits *fits,	// FITS handle
			psMetadata *header, // FITS header
			const psArray *pixels,// Array of images
			const char *extname // Extension name
			)
{
    // Check NAXIS 3
    if (pixels->n > 1) {
	psMetadataAdd(header, PS_LIST_TAIL, "NAXIS3", PS_META_S32 | PS_META_REPLACE, "Added by pmFPAWrite",
		      pixels->n);
    }

    (void)psFitsMoveExtName(fits, extname); // Try to move, even if it fails
    for (int i = 0; i < pixels->n; i++) {
	if (! psFitsWriteImage(fits, header, pixels->data[i], i)) {
	    psError(PS_ERR_IO, false, "Unable to write plane %d to %s.\n", i, extname);
	    return false;
	}
    }
    psFitsSetExtName(fits, extname);

    return true;
}



bool pmFPAWrite(psFits *fits,		// FITS file to which to write
		papFPA *fpa 		// FPA to write
		)
{
    psArray *chips = fpa->chips;	// Array of chips

    for (int i = 0; i < chips->n; i++) {
	papChip *chip = chips->data[i];	// Chip of interest
	psArray *cells = chip->cells;	// Array of cells

	if (chip->extname) {
	    if (! writePixels(fits, chip->header, chip->pixels, chip->extname)) {
		return false;
	    }
	}

	for (int j = 0; j < cells->n; j++) {
	    papCell *cell = cells->data[j]; // Cell of interest

	    if (cell->extname) {
		if (!writePixels(fits, cell->header, cell->pixels, cell->extname)) {
		    return false;
		}
	    }
	}
    }
    
    return true;
}
