# include "psphotInternal.h"

// add newly selected sources to the existing list of sources
bool psphotMergeSources (psArray *oldSources, psArray *newSources) {

    for (int i = 0; i < newSources->n; i++) {
        pmSource *source = newSources->data[i];
        psArrayAdd (oldSources, 100, source);
    }
    return true;
}

// merge the externally supplied sources with the existing sources.  mark them as having
// mode PM_SOURCE_MODE_EXTERNAL
bool psphotLoadExtSources (pmConfig *config, const pmFPAview *view, psArray *sources) {

    // find the currently selected readout
    pmReadout  *readout = pmFPAfileThisReadout (config->files, view, "PSPHOT.INPUT.CMF");
    if (!readout) {
        psLogMsg ("psphot", 3, "no external sources supplied");
        return true;
    }

    psArray *extSources = psMetadataLookupPtr (NULL, readout->analysis, "PSPHOT.SOURCES");
    if (!extSources) {
        psLogMsg ("psphot", 3, "no external sources for this readout");
        return true;
    }

    for (int i = 0; i < extSources->n; i++) {
        pmSource *source = extSources->data[i];
        source->mode |= PM_SOURCE_MODE_EXTERNAL;
        pmModel *model = source->modelPSF;

        float xpos = model->params->data.F32[PM_PAR_XPOS];
        float ypos = model->params->data.F32[PM_PAR_YPOS];

        source->peak = pmPeakAlloc(xpos, ypos, 1.0, PM_PEAK_LONE);
        source->peak->xf = xpos;
        source->peak->yf = ypos;
        source->peak->flux = 1.0;

        // drop the loaded source modelPSF
        psFree (source->modelPSF);
        source->modelPSF = NULL;
    }

    psphotMergeSources (sources, extSources);
    psLogMsg ("psphot", 3, "%ld external sources merged to yield %ld total sources", extSources->n, sources->n);

    return true;
}
