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

#include "pmFPA.h"
#include "pmHDU.h"
#include "pmConcepts.h"


bool pmCellWrite(pmCell *cell,          // Cell to write
                 psFits *fits,          // FITS file to which to write
                 psDB *db               // Database handle for "concepts" update
                )
{
    pmConceptsWriteCell(cell, PM_CONCEPT_SOURCE_HEADER | PM_CONCEPT_SOURCE_CAMERA | PM_CONCEPT_SOURCE_DEFAULTS,
                        false, NULL);

    pmHDU *hdu = cell->hdu;             // The HDU
    if (hdu && !pmHDUWrite(hdu, fits)) {
        psError(PS_ERR_IO, false, "Unable to write HDU for Chip.\n");
        return false;
    }

    return true;
}


bool pmChipWrite(pmChip *chip,          // Chip to write
                 psFits *fits,          // FITS file to which to write
                 psDB *db               // Database handle for "concepts" update
                )
{
    pmConceptsWriteChip(chip, PM_CONCEPT_SOURCE_HEADER | PM_CONCEPT_SOURCE_CAMERA | PM_CONCEPT_SOURCE_DEFAULTS,
                        false, NULL);

    pmHDU *hdu = chip->hdu;             // The HDU
    if (hdu && !pmHDUWrite(hdu, fits)) {
        psError(PS_ERR_IO, false, "Unable to write HDU for Chip.\n");
        return false;
    }

    bool success = true;                // Success of writing
    psArray *cells = chip->cells;       // Array of cells
    for (int i = 0; i < cells->n; i++) {
        pmCell *cell = cells->data[i];  // The cell of interest
        success |= pmCellWrite(cell, fits, db);
    }

    return success;
}




bool pmFPAWrite(pmFPA *fpa,             // FPA to write
                psFits *fits,           // FITS file to which to write
                psDB *db                // Database handle for "concepts" update
               )
{
    pmConceptsWriteFPA(fpa, PM_CONCEPT_SOURCE_HEADER | PM_CONCEPT_SOURCE_CAMERA | PM_CONCEPT_SOURCE_DEFAULTS,
                       NULL);

    pmHDU *hdu = fpa->hdu;              // The HDU
    if (hdu && !pmHDUWrite(hdu, fits)) {
        psError(PS_ERR_IO, false, "Unable to write HDU for FPA.\n");
        return false;
    }

    bool success = true;                // Success of writing
    psArray *chips = fpa->chips;        // Array of chips
    for (int i = 0; i < chips->n; i++) {
        pmChip *chip = chips->data[i];  // The chip of interest
        success |= pmChipWrite(chip, fits, db);
    }

    return success;
}

