# include "psastroStandAlone.h"
// this loop loads the data from the input files and selects the
// brighter stars for astrometry
// at the end of this function, the complete stellar data is loaded
// into the correct fpa structure locations (readout.analysis:PSPHOT.SOURCES)

// all of the different astrometry analysis modes use the same data load loop
bool psastroDataLoad (pmConfig *config) {

    pmChip *chip;
    pmCell *cell;
    pmReadout *readout;

    // select the current recipe
    psMetadata *recipe  = psMetadataLookupPtr (NULL, config->recipes, PSASTRO_RECIPE);
    if (!recipe) {
	psError(PSASTRO_ERR_CONFIG, true, "Can't find PSASTRO recipe!\n");
	return false;
    }

    // select the input data sources
    pmFPAfile *input = psMetadataLookupPtr (NULL, config->files, "PSASTRO.INPUT");
    if (!input) {
	psError(PSASTRO_ERR_CONFIG, true, "Can't find input data!\n");
	return false;
    }

    // de-activate all files except PSASTRO.INPUT
    pmFPAfileActivate (config->files, false, NULL);
    pmFPAfileActivate (config->files, true, "PSASTRO.INPUT");

    pmFPAview *view = pmFPAviewAlloc (0);

    // files associated with the science image
    pmFPAfileIOChecks (config, view, PM_FPA_BEFORE);

    while ((chip = pmFPAviewNextChip (view, input->fpa, 1)) != NULL) {
        psTrace ("psastro", 4, "Chip %d: %x %x\n", view->chip, chip->file_exists, chip->process);
        if (!chip->process || !chip->file_exists) { continue; }
	pmFPAfileIOChecks (config, view, PM_FPA_BEFORE);

	while ((cell = pmFPAviewNextCell (view, input->fpa, 1)) != NULL) {
            psTrace ("psastro", 4, "Cell %d: %x %x\n", view->cell, cell->file_exists, cell->process);
            if (!cell->process || !cell->file_exists) { continue; }
	    pmFPAfileIOChecks (config, view, PM_FPA_BEFORE);

	    // process each of the readouts
	    while ((readout = pmFPAviewNextReadout (view, input->fpa, 1)) != NULL) {
		pmFPAfileIOChecks (config, view, PM_FPA_BEFORE);
		if (! readout->data_exists) { continue; }

		psastroConvertReadout (readout, recipe);

		pmFPAfileIOChecks (config, view, PM_FPA_AFTER);
	    }
	    pmFPAfileIOChecks (config, view, PM_FPA_AFTER);
	}
	pmFPAfileIOChecks (config, view, PM_FPA_AFTER);
    }
    pmFPAfileIOChecks (config, view, PM_FPA_AFTER);
    psFree (view);
    return true;
}

