/** @file  pmPSF_IO.c
 *
 * This file contains functions to read and write PSF models using the psMetadata Config file
 * format.
 *
 *  @author EAM, IfA
 *
 *  @version $Revision: 1.21.2.1 $ $Name: not supported by cvs2svn $
 *  @date $Date: 2007-09-07 20:30:37 $
 *
 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
 *
 */

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

/*****************************************************************************/
/* INCLUDE FILES                                                             */
/*****************************************************************************/

#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 "pmPeaks.h"
#include "pmMoments.h"
#include "pmGrowthCurve.h"
#include "pmResiduals.h"
#include "pmTrend2D.h"
#include "pmPSF.h"
#include "pmModel.h"
#include "pmPSF_IO.h"
#include "pmSource.h"
#include "pmModelClass.h"
#include "pmSourceIO.h"

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

    if (view->chip == -1) {
        bool exists = pmPSFmodelCheckDataStatusForFPA (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 = pmPSFmodelCheckDataStatusForChip (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;
    }
    psError(PS_ERR_IO, false, "PSF only valid at the chip level");
    return false;
}

bool pmPSFmodelCheckDataStatusForFPA (const pmFPA *fpa) {

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

bool pmPSFmodelCheckDataStatusForChip (const pmChip *chip) {

    bool status;

    // select the psf of interest
    pmPSF *psf = psMetadataLookupPtr(&status, chip->analysis, "PSPHOT.PSF");
    return psf ? true : false;
}

bool pmPSFmodelWriteForView (const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{

    pmFPA *fpa = file->fpa;

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

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

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

    psError(PS_ERR_IO, false, "PSF must be written at the chip level");
    return false;
}

// read in all chip-level PSFmodel files for this FPA
bool pmPSFmodelWriteFPA (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 (!pmPSFmodelWriteChip (chip, view, file, config)) {
            psError(PS_ERR_IO, false, "Failed to write PSF for %dth chip", i);
            return false;
        }
    }
    return true;
}

// read in all cell-level PSFmodel files for this chip
bool pmPSFmodelWriteChip (pmChip *chip, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{
    if (!pmPSFmodelWrite (chip->analysis, view, file, config)) {
	psError(PS_ERR_IO, false, "Failed to write PSF for chip");
	return false;
    }
    return true;
}

// for a pmPSF supplied on the analysis metadata, we write out
// - image header        : FITS Image NAXIS = 0
// - psf table (+header) : FITS Table
// - psf resid (+header) : FITS Image
// if needed, we also write out a PHU blank header
bool pmPSFmodelWrite (psMetadata *analysis, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{
    bool status;
    pmHDU *hdu;
    char *headName, *tableName, *residName;

    if (!analysis) return false;

    // 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 'pmPSF_WritePHU' function and called
    // from pmFPAfileIO.c.

    // define the EXTNAME values used for image header, table data, and residual image segments
    {
	// 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, "PSF.HEAD");
	if (!rule) {
	    psError(PS_ERR_UNKNOWN, false, "missing entry for PSF.HEAD in EXTNAME.RULES in camera.config");
	    return false;
	}
	headName = pmFPAfileNameFromRule (rule, file, view);

	// EXTNAME for table data
	rule = psMetadataLookupStr(&status, menu, "PSF.TABLE");
	if (!rule) {
	    psError(PS_ERR_UNKNOWN, false, "missing entry for PSF.TABLE in EXTNAME.RULES in camera.config");
	    psFree (headName);
	    return false;
	}
	tableName = pmFPAfileNameFromRule (rule, file, view);

	// EXTNAME for resid data
	rule = psMetadataLookupStr(&status, menu, "PSF.RESID");
	if (!rule) {
	    psError(PS_ERR_UNKNOWN, false, "missing entry for PSF.RESID in EXTNAME.RULES in camera.config");
	    psFree (headName);
	    psFree (tableName);
	    return false;
	}
	residName = pmFPAfileNameFromRule (rule, file, view);
    }

    // write out the IMAGE header segment
    // this header block is new, write it to disk
    if (hdu->header != file->header) {
	// add EXTNAME, EXTHEAD, EXTTYPE to header
	psMetadataAddStr (hdu->header, PS_LIST_TAIL, "EXTTABLE", PS_META_REPLACE, "name of table extension", tableName);
	psMetadataAddStr (hdu->header, PS_LIST_TAIL, "EXTRESID", PS_META_REPLACE, "name of resid extension", residName);
	psMetadataAddStr (hdu->header, PS_LIST_TAIL, "EXTTYPE", PS_META_REPLACE, "extension type", "IMAGE");
	if (!file->wrote_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);
	    file->wrote_phu = true;
	}

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

    // select the psf of interest
    pmPSF *psf = psMetadataLookupPtr (&status, analysis, "PSPHOT.PSF");
    if (!psf) {
	psError(PS_ERR_UNKNOWN, true, "missing PSF for this analysis metadata");
	psFree (tableName);
	psFree (residName);
	return false;
    }

    // write the PSF model parameters in a FITS table
    { 
	// we need to write a header for the table,
	psMetadata *header = psMetadataAlloc();

	char *modelName = pmModelClassGetName (psf->type);
	psMetadataAddStr (header, PS_LIST_TAIL, "PSF_NAME", 0, "PSF model name", modelName);

	psMetadataAddBool (header, PS_LIST_TAIL, "POISSON",  0, "Use Poisson errors in fits?", psf->poissonErrors);

	int nPar = pmModelClassParameterCount (psf->type)    ;
	psMetadataAdd (header, PS_LIST_TAIL, "PSF_NPAR", PS_DATA_S32, "PSF model parameter count", nPar);

	// save the dimensions of each parameter
	for (int i = 0; i < nPar; i++) {
	    char name[9];
	    psPolynomial2D *poly = psf->params->data[i];
	    if (poly == NULL) continue;
	    snprintf (name, 9, "PAR%02d_NX", i);
	    psMetadataAddS32 (header, PS_LIST_TAIL, name, 0, "", poly->nX);
	    snprintf (name, 9, "PAR%02d_NY", i);
	    psMetadataAddS32 (header, PS_LIST_TAIL, name, 0, "", poly->nY);
	}

	// other required information describing the PSF
	psMetadataAddF32  (header, PS_LIST_TAIL, "AP_RESID", 0, "aperture residual", psf->ApResid);
	psMetadataAddF32  (header, PS_LIST_TAIL, "AP_ERROR", 0, "aperture residual scatter", psf->dApResid);
	psMetadataAddF32  (header, PS_LIST_TAIL, "CHISQ",    0, "chi-square for fit", psf->chisq);
	psMetadataAddS32  (header, PS_LIST_TAIL, "NSTARS",   0, "number of stars used to measure PSF", psf->nPSFstars);

	// XXX can we drop this now?
	psMetadataAddF32 (header, PS_LIST_TAIL, "SKY_BIAS", PS_DATA_F32, "sky bias level", psf->skyBias);

	// build a FITS table of the PSF parameters
	psArray *psfTable = psArrayAllocEmpty (100);
	for (int i = 0; i < nPar; i++) {
	    psPolynomial2D *poly = psf->params->data[i];
	    if (poly == NULL) continue; // skip unset parameters (eg, XPOS)
	    for (int ix = 0; ix <= poly->nX; ix++) {
		for (int iy = 0; iy <= poly->nY; iy++) {

		    psMetadata *row = psMetadataAlloc ();
		    psMetadataAddS32 (row, PS_LIST_TAIL, "MODEL_TERM", 0, "", i);
		    psMetadataAddS32 (row, PS_LIST_TAIL, "X_POWER",    0, "", ix);
		    psMetadataAddS32 (row, PS_LIST_TAIL, "Y_POWER",    0, "", iy);
		    psMetadataAddF32 (row, PS_LIST_TAIL, "VALUE",      0, "", poly->coeff[ix][iy]);
		    psMetadataAddF32 (row, PS_LIST_TAIL, "ERROR",      0, "", poly->coeffErr[ix][iy]);
		    psMetadataAddU8  (row, PS_LIST_TAIL, "MASK",       0, "", poly->mask[ix][iy]);

		    psArrayAdd (psfTable, 100, row);
		    psFree (row);
		}
	    }
	}

	// write an empty FITS segment if we have no PSF information
	if (psfTable->n == 0) {
	    // XXX this is probably an error (if we have a PSF, how do we have no data?)
	    psFitsWriteBlank (file->fits, header, tableName);
	} else {
	    psTrace ("pmFPAfile", 5, "writing psf data %s\n", tableName);
	    if (!psFitsWriteTable (file->fits, header, psfTable, tableName)) {
		psError(PS_ERR_IO, false, "writing psf table data %s\n", tableName);
		psFree (tableName);
		psFree (residName);
		psFree (psfTable);
		psFree (header);
		return false;
	    }
	}
	psFree (tableName);
	psFree (psfTable);
	psFree (header);
    }

    // write the residual images (3D)
    {
	psMetadata *header = psMetadataAlloc ();
	if (psf->residuals == NULL) {
	    // set some header keywords to make it clear there are no residuals?
	    psFitsWriteBlank (file->fits, header, residName);
	    psFree (residName);
	    psFree (header);
	    return true;
	}

	psMetadataAddS32 (header, PS_LIST_TAIL, "XBIN",    0, "", psf->residuals->xBin);
	psMetadataAddS32 (header, PS_LIST_TAIL, "YBIN",    0, "", psf->residuals->yBin);
	psMetadataAddS32 (header, PS_LIST_TAIL, "XCENTER", 0, "", psf->residuals->xCenter);
	psMetadataAddS32 (header, PS_LIST_TAIL, "YCENTER", 0, "", psf->residuals->yCenter);

	// write the residuals as three planes of the image
	// this call creates an extension with NAXIS3 = 3
	if (psf->residuals->Rx) {
	    // this call creates an extension with NAXIS3 = 3
	    psArray *images = psArrayAllocEmpty (3);
	    psArrayAdd (images, 1, psf->residuals->Ro);
	    psArrayAdd (images, 1, psf->residuals->Rx);
	    psArrayAdd (images, 1, psf->residuals->Ry);

	    psFitsWriteImageCube (file->fits, header, images, residName);
	    psFree (images);
	} else {
	    // this call creates an extension with NAXIS3 = 1
	    psFitsWriteImage(file->fits, header, psf->residuals->Ro, 0, residName);
	}
	psFree (residName);
	psFree (header);
    }

    return true;

    // XXX save the growth curve
    // XXX save ApTrend (as image?)

# if (0)
    // build a FITS table of the fit to the Aperture Residuals
    psArray *apresTable = psArrayAllocEmpty (100);
    psPolynomial4D *poly = psf->ApTrend;
    for (int ix = 0; ix < poly->nX; ix++) {
        for (int iy = 0; iy < poly->nY; iy++) {

            row = psMetadataAlloc ();
            psMetadataAddS32 (row, PS_LIST_TAIL, "X_POWER",    0, "", ix);
            psMetadataAddS32 (row, PS_LIST_TAIL, "Y_POWER",    0, "", iy);
            psMetadataAddF32 (row, PS_LIST_TAIL, "VALUE",      0, "", poly->coeff[ix][iy]);
            psMetadataAddF32 (row, PS_LIST_TAIL, "ERROR",      0, "", poly->coeffErr[ix][iy]);
            psMetadataAddU8  (row, PS_LIST_TAIL, "MASK",       0, "", poly->mask[ix][iy]);

            psArrayAdd (psfTable, 100, row);
            psFree (row);
        }
    }
# endif
}

// if this file needs to have a PHU written out, write one
bool pmPSFmodelWritePHU (const pmFPAview *view, pmFPAfile *file, const pmConfig *config) {

    // not needed if already written
    if (file->wrote_phu) return true;

    // not needed if not FPA
    // XXX this prevents us from defining a SPLIT/MEF CMF file...
    if (file->fileLevel != PM_FPA_LEVEL_FPA) return true;

    // not needed if only one chip
    if (file->fpa->chips->n == 1) return true;

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

    // if there is no PHU, this is a single header+image (extension-less) file. This could be
    // the case for an input SPLIT set of files being written out as a MEF.  if there is a PHU,
    // write it out as a 'blank'
    psMetadata *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);
	}
    }

    psMetadataAddBool (outhead, PS_LIST_TAIL, "EXTEND", PS_META_REPLACE, "this file has extensions", true);
    psFitsWriteBlank (file->fits, outhead, "");
    file->wrote_phu = true;

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

    return true;
}

bool pmPSFmodelReadForView (const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{

    pmFPA *fpa = file->fpa;

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

    if (view->chip >= fpa->chips->n) {
        psAbort("Programming error: view does not apply to FPA.");
    }
    pmChip *chip = fpa->chips->data[view->chip];

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

    psError(PS_ERR_IO, false, "PSF must be read at the chip level");
    return false;
}

// read in all chip-level PSFmodel files for this FPA
bool pmPSFmodelReadFPA (pmFPA *fpa, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{
    bool success = true;                // Was everything successful?
    for (int i = 0; i < fpa->chips->n; i++) {
        pmChip *chip = fpa->chips->data[i];
        success &= pmPSFmodelReadChip(chip, view, file, config);
    }
    return success;
}

// read in all cell-level PSFmodel files for this chip
bool pmPSFmodelReadChip (pmChip *chip, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{
    if (!pmPSFmodelRead (chip->analysis, view, file, config)) {
	psError(PS_ERR_IO, false, "Failed to write PSF for chip");
	return false;
    }
    return true;
}

// for each Readout (ie, analysed image), we write out: header + table with PSF model parameters,
// and header + image for the PSF residual images
bool pmPSFmodelRead (psMetadata *analysis, const pmFPAview *view, pmFPAfile *file, const pmConfig *config)
{
    bool status;
    char *rule = NULL;
    psMetadata *header = NULL;

    psTrace ("psModules.objects", 5, "read psf model for %s\n", file->filename);

    // 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 table data
    rule = psMetadataLookupStr(&status, menu, "PSF.TABLE");
    if (!rule) {
        psError(PS_ERR_UNKNOWN, true, "missing entry for PSF.TABLE in EXTNAME.RULES in camera.config");
        return false;
    }
    char *tableName = pmFPAfileNameFromRule (rule, file, view);
    // EXTNAME for residual images
    rule = psMetadataLookupStr(&status, menu, "PSF.RESID");
    if (!rule) {
        psError(PS_ERR_UNKNOWN, true, "missing entry for PSF.RESID in EXTNAME.RULES in camera.config");
        return false;
    }
    char *imageName = pmFPAfileNameFromRule (rule, file, view);

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

    // load the PSF model table header
    header = psFitsReadHeader (NULL, file->fits);
    if (!header) psAbort("cannot read table header");

    // load the PSF model parameters from the FITS table
    char *modelName = psMetadataLookupStr (&status, header, "PSF_NAME");
    pmModelType type = pmModelClassGetType (modelName);
    if (type == -1) {
        psError(PS_ERR_UNKNOWN, true, "invalid model name %s in psf file %s", modelName, file->filename);
        return false;
    }

    bool poissonErrors = psMetadataLookupBool (&status, header, "POISSON");

    // we determine the PSF parameter polynomials from the MD-defined polynomials
    pmPSF *psf = pmPSFAlloc (type, poissonErrors, NULL);

    // check the number of expected parameters
    int nPar = psMetadataLookupS32 (&status, header, "PSF_NPAR");
    if (nPar != pmModelClassParameterCount (psf->type))
        psAbort("mismatch model par count");

    // load the dimensions of each parameter
    for (int i = 0; i < nPar; i++) {
        char name[9];
        snprintf (name, 9, "PAR%02d_NX", i);
        int nXorder = psMetadataLookupS32 (&status, header, name);
	if (!status) continue;		// not all parameters are defined
        snprintf (name, 9, "PAR%02d_NY", i);
        int nYorder = psMetadataLookupS32 (&status, header, name);
	if (!status) {
	    psError(PS_ERR_UNKNOWN, true, "inconsistent PSF header: NX defined for PAR %d, but no NY", i);
	    return false;
	}
        psf->params->data[i] = psPolynomial2DAlloc (PS_POLYNOMIAL_ORD, nXorder, nYorder);
    }

    // other required information describing the PSF
    psf->ApResid   = psMetadataLookupF32 (&status, header, "AP_RESID");
    psf->dApResid  = psMetadataLookupF32 (&status, header, "AP_ERROR");
    psf->chisq     = psMetadataLookupF32 (&status, header, "CHISQ");
    psf->nPSFstars = psMetadataLookupS32 (&status, header, "NSTARS");

    // XXX can we drop this now?
    psf->skyBias   = psMetadataLookupF32 (&status, header, "SKY_BIAS");

    // read the raw table data
    psArray *table = psFitsReadTable (file->fits);

    // fill in the matching psf->params entries
    for (int i = 0; i < table->n; i++) {
        psMetadata *row = table->data[i];
        int iPar = psMetadataLookupS32 (&status, row, "MODEL_TERM");
        int xPow = psMetadataLookupS32 (&status, row, "X_POWER");
        int yPow = psMetadataLookupS32 (&status, row, "Y_POWER");
        // XXX sanity check here

        psPolynomial2D *poly = psf->params->data[iPar];
	if (poly == NULL) {
	    psError(PS_ERR_UNKNOWN, true, "values for parameter %d, but missing NX", iPar);
	    return false;
	}

        poly->coeff[xPow][yPow]    = psMetadataLookupF32 (&status, row, "VALUE");
        poly->coeffErr[xPow][yPow] = psMetadataLookupF32 (&status, row, "ERROR");
        poly->mask[xPow][yPow]     = psMetadataLookupU8  (&status, row, "MASK");
    }
    psFree (header);
    psFree (table);

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

    header = psFitsReadHeader (NULL, file->fits);
    int Naxis = psMetadataLookupS32 (&status, header, "NAXIS");
    if (Naxis != 0) {

        int Nx = psMetadataLookupS32 (&status, header, "NAXIS1");
        int Ny = psMetadataLookupS32 (&status, header, "NAXIS2");
        int Nz = psMetadataLookupS32 (&status, header, "NAXIS3");

        int xBin  = psMetadataLookupS32 (&status, header, "XBIN");
        int yBin  = psMetadataLookupS32 (&status, header, "YBIN");

        int xSize = Nx / xBin;
        int ySize = Ny / yBin;

        psf->residuals = pmResidualsAlloc (xSize, ySize, xBin, yBin);

        psf->residuals->xCenter = psMetadataLookupS32 (&status, header, "XCENTER");
        psf->residuals->yCenter = psMetadataLookupS32 (&status, header, "YCENTER");

        psRegion fullImage = {0, 0, 0, 0};
        psFitsReadImageBuffer(psf->residuals->Ro, file->fits, fullImage, 0); // Desired pixels
        if (Nz > 1) {
            assert (Nz == 3);
            psFitsReadImageBuffer(psf->residuals->Rx, file->fits, fullImage, 1); // Desired pixels
            psFitsReadImageBuffer(psf->residuals->Ry, file->fits, fullImage, 2); // Desired pixels
        }
    }

    psMetadataAdd (analysis, PS_LIST_TAIL, "PSPHOT.PSF",     PS_DATA_UNKNOWN,  "psphot psf", psf);
    psFree (psf);

    psFree (tableName);
    psFree (imageName);
    psFree (header);

    return true;
}

// create a psMetadata representation (human-readable) of a psf model
psMetadata *pmPSFtoMetadata (psMetadata *metadata, pmPSF *psf)
{

    if (metadata == NULL) {
        metadata = psMetadataAlloc ();
    }

    char *modelName = pmModelClassGetName (psf->type);
    psMetadataAdd (metadata, PS_LIST_TAIL, "PSF_MODEL_NAME", PS_DATA_STRING, "PSF model name", modelName);

    int nPar = pmModelClassParameterCount (psf->type)    ;
    psMetadataAdd (metadata, PS_LIST_TAIL, "PSF_MODEL_NPAR", PS_DATA_S32, "PSF model parameter count", nPar);

    for (int i = 0; i < nPar; i++) {
        psPolynomial2D *poly = psf->params->data[i];
        if (poly == NULL)
            continue;
        psPolynomial2DtoMetadata (metadata, poly, "PSF_PAR%02d", i);
    }

    // XXX fix this
    psWarning ("APTREND is currently missing");
    // psPolynomial4DtoMetadata (metadata, psf->ApTrend, "APTREND");

    psMetadataAdd (metadata, PS_LIST_TAIL, "PSF_AP_RESID", PS_DATA_F32, "aperture residual", psf->ApResid);
    psMetadataAdd (metadata, PS_LIST_TAIL, "PSF_dAP_RESID", PS_DATA_F32, "aperture residual scatter", psf->dApResid);
    psMetadataAdd (metadata, PS_LIST_TAIL, "PSF_SKY_BIAS", PS_DATA_F32, "sky bias level", psf->skyBias);

    psMetadataAdd (metadata, PS_LIST_TAIL, "PSF_CHISQ", PS_DATA_F32, "chi-square for fit", psf->chisq);
    psMetadataAdd (metadata, PS_LIST_TAIL, "PSF_NSTARS", PS_DATA_S32, "number of stars used to measure PSF", psf->nPSFstars);
    psMetadataAdd (metadata, PS_LIST_TAIL, "PSF_POISSON_ERRORS", PS_DATA_BOOL, "Poisson errors for fits", psf->poissonErrors);

    return metadata;
}

// parse a psMetadata representation (human-readable) of a psf model
pmPSF *pmPSFfromMetadata (psMetadata *metadata)
{

    bool status;
    char keyword[80];

    char *modelName = psMetadataLookupPtr (&status, metadata, "PSF_MODEL_NAME");
    pmModelType type = pmModelClassGetType (modelName);

    bool poissonErrors = psMetadataLookupPtr (&status, metadata, "PSF_POISSON_ERRORS");
    if (!status)
        poissonErrors = true;

    // we determine the PSF parameter polynomials from the MD-defined polynomials
    pmPSF *psf = pmPSFAlloc (type, poissonErrors, NULL);

    int nPar = psMetadataLookupS32 (&status, metadata, "PSF_MODEL_NPAR");
    if (nPar != pmModelClassParameterCount (psf->type))
        psAbort("mismatch model par count");

    // un-fitted terms, not in the Metadata, are left NULL
    // XXX add a double-check of the expected number?
    for (int i = 0; i < nPar; i++) {
        sprintf (keyword, "PSF_PAR%02d", i);
        psMetadata *folder = psMetadataLookupPtr (&status, metadata, keyword);
        if (!status)
            continue;
        psPolynomial2D *poly = psPolynomial2DfromMetadata (folder);
        psFree (psf->params->data[i]);
        psf->params->data[i] = poly;
    }

    // load the APTREND data
    // XXX fix this to work with pmTrend2D
    psWarning ("APTREND is not being read");
    # if (0)
    sprintf (keyword, "APTREND");
    psMetadata *folder = psMetadataLookupPtr (&status, metadata, keyword);
    psPolynomial4D *poly = psPolynomial4DfromMetadata (folder);
    psFree (psf->ApTrend);
    psf->ApTrend = poly;
    # endif

    psf->ApResid = psMetadataLookupF32 (&status, metadata, "PSF_AP_RESID");
    psf->dApResid = psMetadataLookupF32 (&status, metadata, "PSF_dAP_RESID");
    psf->skyBias = psMetadataLookupF32 (&status, metadata, "PSF_SKY_BIAS");

    psf->chisq = psMetadataLookupF32 (&status, metadata, "PSF_CHISQ");
    psf->nPSFstars = psMetadataLookupS32 (&status, metadata, "PSF_NSTARS");

    psFree (metadata);
    return (psf);
}
