/** @file  pmSourceIO.c
 *
 *  @author EAM, IfA
 *
 *  @version $Revision: 1.39 $ $Name: not supported by cvs2svn $
 *  @date $Date: 2007-05-03 20:04:31 $
 *
 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <strings.h>		/* for strn?casecmp */
#include <pslib.h>

#include "pmConfig.h"
#include "pmDetrendDB.h"

#include "pmHDU.h"
#include "pmFPA.h"
#include "pmFPALevel.h"
#include "pmFPAview.h"
#include "pmFPAfile.h"
#include "pmConcepts.h"

#include "pmPeaks.h"
#include "pmMoments.h"
#include "pmGrowthCurve.h"
#include "pmResiduals.h"
#include "pmModel.h"
#include "pmPSF.h"
#include "pmSource.h"
#include "pmModelGroup.h"
#include "pmSourceIO.h"

// translations between psphot object types and dophot object types
int pmSourceGetDophotType (pmSource *source)
{
    switch (source->type) {

      case PM_SOURCE_TYPE_DEFECT:
      case PM_SOURCE_TYPE_SATURATED:
        return (8);

      case PM_SOURCE_TYPE_STAR:
        if (source->mode & PM_SOURCE_MODE_SATSTAR)
            return (10);
        if (source->mode & PM_SOURCE_MODE_POOR)
            return (7);
        if (source->mode & PM_SOURCE_MODE_FAIL)
            return (4);
        return (1);

      case PM_SOURCE_TYPE_EXTENDED:
        return (2);

      default:
        return (0);
    }
    return (0);
}

// translations between psphot object types and dophot object types
bool pmSourceSetDophotType (pmSource *source, int type)
{
    if (type == 4) {
	source->mode |= PM_SOURCE_MODE_FAIL;
    }
    if (type == 7) {
	source->mode |= PM_SOURCE_MODE_POOR;
    }
    if (type == 10) {
	source->mode |= PM_SOURCE_MODE_SATSTAR;
    }

    switch (type) {
      case 1:
      case 4:
      case 7:
      case 10:
	source->type = PM_SOURCE_TYPE_STAR; 
	return true;
      case 2:
	source->type = PM_SOURCE_TYPE_EXTENDED; 
	return true;
      case 8:
	source->type = PM_SOURCE_TYPE_DEFECT; 
	return true;
      default:
	return false;
    }
    return false;
}

// Given a FITS file pointer, write the table of object data
bool pmFPAviewWriteObjects (const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{

    pmFPA *fpa = file->fpa;

    if (view->chip == -1) {
        if (!pmFPAWriteObjects (fpa, view, file, config)) {
            psError(PS_ERR_IO, false, "Failed to write objects from fpa");
            return false;
        }
        return true;
    }

    if (view->chip >= fpa->chips->n) {
        psError(PS_ERR_UNKNOWN, false, "Writing chip == %d (>= chips->n == %ld)", view->chip, fpa->chips->n);
        return false;
    }
    pmChip *chip = fpa->chips->data[view->chip];

    if (view->cell == -1) {
        if (!pmChipWriteObjects (chip, view, file, config)) {
            psError(PS_ERR_IO, false, "Failed to write objects from chip");
            return false;
        }
        return true;
    }

    if (view->cell >= chip->cells->n) {
        psError(PS_ERR_UNKNOWN, false, "Writing cell == %d (>= cells->n == %ld)",
                view->cell, chip->cells->n);
        return false;
    }
    pmCell *cell = chip->cells->data[view->cell];

    if (view->readout == -1) {
        if (!pmCellWriteObjects (cell, view, file, config)) {
            psError(PS_ERR_IO, false, "Failed to write objects from cell");
            return false;
        }

        return true;
    }

    if (view->readout >= cell->readouts->n) {
        psError(PS_ERR_UNKNOWN, false, "Writing readout == %d (>= readouts->n == %ld)",
                view->readout, cell->readouts->n);
        return false;
    }
    pmReadout *readout = cell->readouts->data[view->readout];

    if (!pmReadoutWriteObjects (readout, view, file, config)) {
        psError(PS_ERR_IO, false, "Failed to write objects from readout %d", view->readout);
        return false;
    }

    return true;
}

// read in all chip-level Objects files for this FPA
bool pmFPAWriteObjects (pmFPA *fpa, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{

    for (int i = 0; i < fpa->chips->n; i++) {

        pmChip *chip = fpa->chips->data[i];
        if (!pmChipWriteObjects (chip, view, file, config)) {
            psError(PS_ERR_IO, false, "Failed to write %dth chip", i);
            return false;
        }
    }
    return true;
}

// read in all cell-level Objects files for this chip
bool pmChipWriteObjects (pmChip *chip, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{

    for (int i = 0; i < chip->cells->n; i++) {

        pmCell *cell = chip->cells->data[i];
        if (!pmCellWriteObjects (cell, view, file, config)) {
            psError(PS_ERR_IO, false, "Failed to write %dth cell", i);
            return false;
        }
    }
    return true;
}

// read in all readout-level Objects files for this cell
bool pmCellWriteObjects (pmCell *cell, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{

    for (int i = 0; i < cell->readouts->n; i++) {

        pmReadout *readout = cell->readouts->data[i];
        if (!pmReadoutWriteObjects (readout, view, file, config)) {
            psError(PS_ERR_IO, false, "Failed to write %dth readout", i);
            return false;
        }
    }
    return true;
}

// write out all readout-level Objects files for this cell
bool pmReadoutWriteObjects (pmReadout *readout, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{

    bool status;
    char *exttype;
    char *realname;
    char *filename;
    char *dataname;
    char *headname;
    pmHDU *hdu;
    pmHDU *phu;
    psMetadata *updates;
    psMetadata *outhead;

    // XXX if sources is NULL, skip the cell or write out empty tables?
    psArray *sources = psMetadataLookupPtr (&status, readout->analysis, "PSPHOT.SOURCES");
    if (sources == NULL)
        return true;

    bool create = file->mode == PM_FPA_MODE_WRITE ? true : false;

    switch (file->type) {
      case PM_FPA_FILE_RAW:
        filename = pmFPAfileNameFromRule (file->filerule, file, view);
        realname = pmConfigConvertFilename (filename, config, create);
        pmSourcesWriteRAW (sources, realname);
        psFree (realname);
        psFree (filename);
        break;

      case PM_FPA_FILE_OBJ:
        filename = pmFPAfileNameFromRule (file->filerule, file, view);
        realname = pmConfigConvertFilename (filename, config, create);
        pmSourcesWriteOBJ (sources, realname);
        psFree (realname);
        psFree (filename);
        break;

      case PM_FPA_FILE_SX:
        filename = pmFPAfileNameFromRule (file->filerule, file, view);
        realname = pmConfigConvertFilename (filename, config, create);
        pmSourcesWriteSX (sources, realname);
        psFree (realname);
        psFree (filename);
        break;

      case PM_FPA_FILE_CMP:
        // a SPLIT format : only one header and object table per file
        hdu = pmFPAviewThisHDU (view, file->fpa);
        filename = pmFPAfileNameFromRule (file->filerule, file, view);
        realname = pmConfigConvertFilename (filename, config, create);

        // copy the header to an output header, add the output header data
        outhead = psMetadataCopy (NULL, hdu->header);

        // copy over the entries saved by PSPHOT
        updates = psMetadataLookupPtr (NULL, readout->analysis, "PSPHOT.HEADER");
        if (updates) {
            psMetadataCopy (outhead, updates);
        }

        // copy over the entries saved by PSASTRO
        updates = psMetadataLookupPtr (NULL, readout->analysis, "PSASTRO.HEADER");
        if (updates) {
            psMetadataCopy (outhead, updates);
        }

        bool status = pmSourcesWriteCMP (sources, realname, outhead);
        psFree (outhead);
        psFree (realname);
        psFree (filename);

        if (!status) {
            psError(PS_ERR_IO, false, "Failed to write CMP file\n");
            return false;
        }
        break;

      case PM_FPA_FILE_CMF:
        // write a PHU? (only if input image is MEF)
        // write a header? (only if this is the first readout for cell)
        //   note that the file->header is set to track the last hdu->header written
        // write the data? (always?)

        // get the current header
        hdu = pmFPAviewThisHDU (view, file->fpa);

        // if file does not yet have a PHU, attempt to write one to disk
        // we only need a PHU if chips->n > 1 and file->fileLevel == FPA
        // otherwise, the chip header fills the PHU location
        // XXX this code could be placed in a 'pmSource_CMF_WritePHU' function and called
        // from pmFPAfileIO.c.
        if ((file->fileLevel == PM_FPA_LEVEL_FPA) && (file->fpa->chips->n > 1) && !file->phu) {

            // find the FPA phu
            phu = pmFPAviewThisPHU (view, file->fpa);

            // if there is no PHU, this is a single header+image (extension-less) file
            // if there is a PHU, write it out as a 'blank'
            outhead = psMetadataAlloc();
            if (phu) {
                psMetadataCopy (outhead, phu->header);
            } else {
                pmConfigConformHeader (outhead, file->format);

                psMetadata *fileData = psMetadataLookupMetadata(NULL, file->format, "FILE"); // File information
                const char *fpaNameHdr = psMetadataLookupStr(NULL, fileData, "FPA.NAME");
                if (fpaNameHdr && strlen(fpaNameHdr) > 0) {
                    const char *fpaName = psMetadataLookupStr(NULL, file->fpa->concepts, "FPA.NAME");
                    psMetadataAddStr(outhead, PS_LIST_TAIL, fpaNameHdr, PS_META_REPLACE, "FPA name", fpaName);
                }
            }

            // if we have mosaic-level astrometry information, add it here:
            updates = psMetadataLookupPtr (&status, file->fpa->analysis, "PSASTRO.HEADER");
            if (updates) {
                psMetadataCopy (outhead, updates);
            }

            psMetadataAddBool (outhead, PS_LIST_TAIL, "EXTEND", PS_META_REPLACE, "this file has extensions", true);
            psFitsWriteBlank (file->fits, outhead, "");
            file->phu = true;
            psTrace ("pmFPAfile", 5, "wrote phu %s (type: %d)\n", file->filename, file->type);
            psFree (outhead);
        }

        // lookup the EXTNAME values used for table data and image header segments
        char *rule = NULL;
        // Menu of EXTNAME rules
        psMetadata *menu = psMetadataLookupMetadata(&status, file->camera, "EXTNAME.RULES");
        if (!menu) {
            psError(PS_ERR_UNKNOWN, true, "missing EXTNAME.RULES in camera.config");
            return false;
        }
        // EXTNAME for image header
        rule = psMetadataLookupStr(&status, menu, "CMF.HEAD");
        if (!rule) {
            psError(PS_ERR_UNKNOWN, true, "missing entry for CMF.HEAD in EXTNAME.RULES in camera.config");
            return false;
        }
        headname = pmFPAfileNameFromRule (rule, file, view);
        // EXTNAME for table data
        rule = psMetadataLookupStr(&status, menu, "CMF.DATA");
        if (!rule) {
            psError(PS_ERR_UNKNOWN, true, "missing entry for CMF.DATA in EXTNAME.RULES in camera.config");
            return false;
        }
        dataname = pmFPAfileNameFromRule (rule, file, view);

        // this header block is new, write it to disk
        if (hdu->header != file->header) {
	    // XXX I was building a new copy, why?  supplement the output header
            // outhead = psMetadataCopy (NULL, hdu->header);

            // add EXTNAME, EXTHEAD, EXTTYPE to header
            // psMetadataAddStr (outhead, PS_LIST_TAIL, "EXTNAME", PS_META_REPLACE, "extension name", headname);
            psMetadataAddStr (hdu->header, PS_LIST_TAIL, "EXTDATA", PS_META_REPLACE, "name of table extension", dataname);
            psMetadataAddStr (hdu->header, PS_LIST_TAIL, "EXTTYPE", PS_META_REPLACE, "extension type", "IMAGE");
            if (!file->phu) {
                // this hdu->header acts as the PHU: set EXTEND to be true
                psMetadataAddBool (hdu->header, PS_LIST_TAIL, "EXTEND", PS_META_REPLACE, "this file has extensions", true);
            }

            // save psphot and psastro metadata in the image and table headers
            updates = psMetadataLookupPtr (&status, readout->analysis, "PSPHOT.HEADER");
            if (updates) {
                psMetadataCopy (hdu->header, updates);
            }
            updates = psMetadataLookupPtr (&status, readout->analysis, "PSASTRO.HEADER");
            if (updates) {
                psMetadataCopy (hdu->header, updates);
            }

            psFitsWriteBlank (file->fits, hdu->header, headname);
            psTrace ("pmFPAfile", 5, "wrote ext head %s (type: %d)\n", file->filename, file->type);
            file->header = hdu->header;
        }

        // create a header to hold the output data
        outhead = psMetadataAlloc ();

        // determine the output table format
        psMetadata *recipe = psMetadataLookupMetadata(&status, config->recipes, "PSPHOT");
        if (!status) {
            psError(PS_ERR_UNKNOWN, true, "missing recipe PSPHOT in config data");
            return false;
        }
        exttype = psMemIncrRefCounter (psMetadataLookupStr(&status, recipe, "OUTPUT.FORMAT"));
        if (!exttype) {
            exttype = psStringCopy ("SMPDATA");
        }

        // write the links to the image header
        psMetadataAddStr (outhead, PS_LIST_TAIL, "EXTHEAD", PS_META_REPLACE, "name of image extension w/", headname);
        psMetadataAddStr (outhead, PS_LIST_TAIL, "EXTTYPE", PS_META_REPLACE, "extension type", exttype);
        psFree (exttype);

        // XXX these are case-sensitive since the EXTYPE is case-sensitive
        status = false;
        if (!strcmp (exttype, "SMPDATA")) {
            status = pmSourcesWrite_SMPDATA (file->fits, sources, file->header, outhead, dataname);
        }
        if (!strcmp (exttype, "PS1_DEV_0")) {
            status = pmSourcesWrite_PS1_DEV_0 (file->fits, sources, file->header, outhead, dataname);
        }

        if (!status) {
            psError(PS_ERR_IO, false, "writing CMF data to %s with format %s\n", file->filename, exttype);
            psFree (headname);
            psFree (dataname);
            psFree (outhead);
            return false;
        }

        psTrace ("pmFPAfile", 5, "wrote ext data %s (type: %d)\n", file->filename, file->type);

        psFree (headname);
        psFree (dataname);
        psFree (outhead);
        break;

      default:
        fprintf (stderr, "warning: type mismatch\n");
        break;
    }
    return true;
}
// a MEF CMF file has: PHU, CELL-HEAD, TABLE, CELL-HEAD, TABLE, TABLE, TABLE...

// Given a FITS file pointer, read the table of object data
// XXX add in error handling
bool pmFPAviewReadObjects (const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{
    pmFPA *fpa = file->fpa;

    if (view->chip == -1) {
        pmFPAReadObjects (fpa, view, file, config);
        return true;
    }

    if (view->chip >= fpa->chips->n) {
        return false;
    }
    pmChip *chip = fpa->chips->data[view->chip];

    if (view->cell == -1) {
        pmChipReadObjects (chip, view, file, config);
        return true;
    }

    if (view->cell >= chip->cells->n) {
        return false;
    }
    pmCell *cell = chip->cells->data[view->cell];

    if (view->readout == -1) {
        pmCellReadObjects (cell, view, file, config);
        return true;
    }

    if (view->readout >= cell->readouts->n) {
        return false;
    }
    pmReadout *readout = cell->readouts->data[view->readout];

    pmReadoutReadObjects (readout, view, file, config);
    return true;
}

// read in all chip-level Objects files for this FPA
bool pmFPAReadObjects (pmFPA *fpa, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{
    for (int i = 0; i < fpa->chips->n; i++) {
        pmChip *chip = fpa->chips->data[i];
        pmChipReadObjects (chip, view, file, config);
    }
    return true;
}

// read in all cell-level Objects files for this chip
bool pmChipReadObjects (pmChip *chip, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{
    chip->data_exists = false;
    for (int i = 0; i < chip->cells->n; i++) {
        pmCell *cell = chip->cells->data[i];
        pmCellReadObjects (cell, view, file, config);
        if (!cell->data_exists) continue;
        chip->data_exists = true;
    }
    return true;
}

// read in all readout-level Objects files for this cell
bool pmCellReadObjects (pmCell *cell, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{
    // multiple readout mode is not yet defined for CMP or CMF files
    // if they have not been allocated, allocate a single readout
    if (!cell->readouts || !cell->readouts->n) {
        pmReadout *readout = pmReadoutAlloc (cell);
        psFree (readout);
    }

    cell->data_exists = false;
    for (int i = 0; i < cell->readouts->n; i++) {
        pmReadout *readout = cell->readouts->data[i];
        pmReadoutReadObjects (readout, view, file, config);
        if (!readout->data_exists) {
            continue;
        }

        // load in the concept information for this cell
        if (!pmConceptsReadCell(cell, PM_CONCEPT_SOURCE_HEADER, true, NULL)) {
            //psError(PS_ERR_UNKNOWN, false, "Failed to read concepts for cell");
            //return false;
            psWarning("Difficulty reading concepts for cell; attempting to proceed.");
        }
        cell->data_exists = true;
    }
    return true;
}

// read in all readout-level Objects files for this cell
bool pmReadoutReadObjects (pmReadout *readout, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{

    bool status;
    psArray *sources = NULL;
    pmHDU *hdu;

    switch (file->type) {
      case PM_FPA_FILE_OBJ:
        psError(PS_ERR_UNKNOWN, true, "OBJ is not supported as an input object format");
        return false;

      case PM_FPA_FILE_SX:
        psError(PS_ERR_UNKNOWN, true, "SX is not supported as an input object format");
        return false;

      case PM_FPA_FILE_CMP:
        // a SPLIT format : only one header and object table per file

        // read in header, if not yet loaded
        hdu = pmFPAviewThisHDU (view, file->fpa);
        if (file->filename)
            psFree (file->filename);
        file->filename = pmFPAfileNameFromRule (file->filerule, file, view);

        // indirect filenames
        if (!strcasecmp (file->filename, "@FILES")) {
            psFree (file->filename);
            char *filesrc = pmFPAfileNameFromRule (file->filesrc, file, view);
            file->filename = psMetadataLookupStr (&status, file->names, filesrc);
            psFree (filesrc);
            if (file->filename == NULL) return false;
            // psMetadataLookupStr just returns a view, file->filename must be protected
            psMemIncrRefCounter (file->filename);
        }

        bool create = file->mode == PM_FPA_MODE_WRITE ? true : false;
        psString realname = pmConfigConvertFilename (file->filename, config, create);

        // read the PHU from this file
        file->fits = psFitsOpen (realname, "r");
        if (hdu->header != NULL) {
            psFree (hdu->header);
        }
        hdu->header = psFitsReadHeader (NULL, file->fits);
        psFitsClose (file->fits);
        file->fits = NULL;

        sources = pmSourcesReadCMP (realname, hdu->header);
        psFree (realname);
        break;

      case PM_FPA_FILE_CMF:
        // read in header, if not yet loaded
        hdu = pmFPAviewThisHDU (view, file->fpa);

        // lookup the EXTNAME values used for table data and image header segments
        char *rule = NULL;
        // Menu of EXTNAME rules
        psMetadata *menu = psMetadataLookupMetadata(&status, file->camera, "EXTNAME.RULES");
        if (!menu) {
            psError(PS_ERR_UNKNOWN, true, "missing EXTNAME.RULES in camera.config");
            return false;
        }
        // EXTNAME for image header
        rule = psMetadataLookupStr(&status, menu, "CMF.HEAD");
        if (!rule) {
            psError(PS_ERR_UNKNOWN, true, "missing entry for CMF.HEAD in EXTNAME.RULES in camera.config");
            return false;
        }
        char *headname = pmFPAfileNameFromRule (rule, file, view);
        // EXTNAME for table data
        rule = psMetadataLookupStr(&status, menu, "CMF.DATA");
        if (!rule) {
            psError(PS_ERR_UNKNOWN, true, "missing entry for CMF.DATA in EXTNAME.RULES in camera.config");
            return false;
        }
        char *dataname = pmFPAfileNameFromRule (rule, file, view);

        // advance to the IMAGE HEADER extension
        if (hdu->header == NULL) {
            // if the IMAGE header does not exist, we have no data for this view
            if (!psFitsMoveExtName (file->fits, headname)) {
                readout->data_exists = false;
                psFree (headname);
                psFree (dataname);
                return true;
            }
            hdu->header = psFitsReadHeader (NULL, file->fits);
        }

        // we need to find the corresponding table EXTNAME.
        // first check the header
        char *extdata = psMetadataLookupStr (NULL, hdu->header, "EXTDATA");
        if (extdata) {
            // if EXTDATA is defined in the header, use that value for 'dataname'
            psFree (dataname);
            dataname = psMemIncrRefCounter (extdata);
        }

        // advance to the table data extension
        // since we have read the IMAGE header, the TABLE header should exist
        if (!psFitsMoveExtName (file->fits, dataname)) {
            psAbort("cannot find data extension %s in %s", dataname, file->filename);
        }

        psMetadata *tableHeader = psFitsReadHeader(NULL, file->fits); // The FITS header
        if (!tableHeader) psAbort("cannot read table header");

        char *exttype = psMetadataLookupStr (NULL, tableHeader, "EXTTYPE");
        if (!exttype) psAbort("cannot read table type");

        // XXX these are case-sensitive since the EXTYPE is case-sensitive
        if (!strcmp (exttype, "SMPDATA")) {
            sources = pmSourcesRead_SMPDATA (file->fits, hdu->header);
        }
        if (!strcmp (exttype, "PS1_DEV_0")) {
            sources = pmSourcesRead_PS1_DEV_0 (file->fits, hdu->header);
        }

        psTrace("psModules.objects", 6, "read CMF table from %s : %s : %s", file->filename, headname, dataname);
        psFree (headname);
        psFree (dataname);
        psFree (tableHeader);
        break;

      default:
        fprintf (stderr, "warning: type mismatch\n");
        break;
    }
    readout->data_exists = true;
    status = psMetadataAdd (readout->analysis, PS_LIST_TAIL, "PSPHOT.SOURCES", PS_DATA_ARRAY, "psphot sources", sources);
    psFree (sources);
    return true;
}

bool pmFPAviewCheckDataStatusForSources (const pmFPAview *view, const pmFPAfile *file)
{
    pmFPA *fpa = file->fpa;

    if (view->chip == -1) {
	bool exists = pmFPACheckDataStatusForSources (fpa);
        return exists;
    }
    if (view->chip >= fpa->chips->n) {
	psError(PS_ERR_IO, true, "Requested chip == %d >= fpa->chips->n == %ld", view->chip, fpa->chips->n);
        return false;
    }
    pmChip *chip = fpa->chips->data[view->chip];

    if (view->cell == -1) {
        bool exists = pmChipCheckDataStatusForSources (chip);
        return exists;
    }
    if (view->cell >= chip->cells->n) {
	psError(PS_ERR_IO, true, "Requested cell == %d >= chip->cells->n == %ld", view->cell, chip->cells->n);
        return false;
    }
    pmCell *cell = chip->cells->data[view->cell];

    if (view->readout == -1) {
        bool exists = pmCellCheckDataStatusForSources (cell);
        return exists;
    }

    if (view->readout >= cell->readouts->n) {
	psError(PS_ERR_IO, true, "Requested readout == %d >= cell->readouds->n == %ld", view->readout, cell->readouts->n);
        return false;
    }
    pmReadout *readout = cell->readouts->data[view->readout];

    bool exists = pmReadoutCheckDataStatusForSources (readout);
    return exists;
}

bool pmFPACheckDataStatusForSources (const pmFPA *fpa) {

    for (int i = 0; i < fpa->chips->n; i++) {
	pmChip *chip = fpa->chips->data[i];
	if (!chip) continue;
	if (pmChipCheckDataStatusForSources (chip)) return true;
    }
    return false;
}

bool pmChipCheckDataStatusForSources (const pmChip *chip) {

    for (int i = 0; i < chip->cells->n; i++) {
	pmCell *cell = chip->cells->data[i];
	if (!cell) continue;
	if (pmCellCheckDataStatusForSources (cell)) return true;
    }
    return false;
}

bool pmCellCheckDataStatusForSources (const pmCell *cell) {

    for (int i = 0; i < cell->readouts->n; i++) {
	pmReadout *readout = cell->readouts->data[i];
	if (!readout) continue;
	if (pmReadoutCheckDataStatusForSources (readout)) return true;
    }
    return false;
}

bool pmReadoutCheckDataStatusForSources (const pmReadout *readout) {

    bool status;

    // select the psf of interest
    pmPSF *psf = psMetadataLookupPtr (&status, readout->analysis, "PSPHOT.SOURCES");
    if (!psf) return false;
    return true;
}

