# include "psastroInternal.h"
// XXX leak free 2006.04.27

// this loop saves the photometry/astrometry data files
bool psastroDataSave (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 output data sources
    pmFPAfile *output = psMetadataLookupPtr (NULL, config->files, "PSASTRO.OUTPUT");
    if (!output) {
	psError(PSASTRO_ERR_CONFIG, true, "Can't find or interpret output file rule PSASTRO.OUTPUT!\n");
	return false;
    }

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

    pmFPAview *view = pmFPAviewAlloc (0);

    // open/load files as needed
    pmFPAfileIOChecks (config, view, PM_FPA_BEFORE);

    while ((chip = pmFPAviewNextChip (view, output->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, output->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, output->fpa, 1)) != NULL) {
		pmFPAfileIOChecks (config, view, PM_FPA_BEFORE);
		if (! readout->data_exists) { continue; }

		pmFPAfileIOChecks (config, view, PM_FPA_AFTER);
	    }
	    pmFPAfileIOChecks (config, view, PM_FPA_AFTER);
	}
	pmFPAfileIOChecks (config, view, PM_FPA_AFTER);
    }
    pmFPAfileIOChecks (config, view, PM_FPA_AFTER);

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

    psFree (view);
    return true;
}
