/** @file  pmSourceIO.c
 *
 *  @author EAM, IfA
 *
 *  @version $Revision: 1.7 $ $Name: not supported by cvs2svn $
 *  @date $Date: 2006-11-29 02:36:38 $
 *
 *  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 <pslib.h>
#include "pmHDU.h"
#include "pmFPA.h"
#include "pmFPAview.h"
#include "pmFPAfile.h"

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

// elixir-mode / sextractor-style output list with fixed line width
bool pmSourcesWriteSX (psArray *sources, char *filename)
{

    psF32 *PAR, *dPAR;
    psEllipseShape shape;
    psEllipseAxes axes;

    psLine *line = psLineAlloc (110);  // 110 is sextractor line length

    FILE *f = fopen (filename, "w");
    if (f == NULL) {
        psLogMsg (__func__, 3, "can't open output file for output %s\n", filename);
        return false;
    }

    // write sources with models
    for (int i = 0; i < sources->n; i++) {
        pmSource *source = (pmSource *) sources->data[i];
        pmModel *model = pmSourceSelectModel (source);
        if (model == NULL)
            continue;

        PAR = model->params->data.F32;
        dPAR = model->dparams->data.F32;

        // pmSourceSextractType (source, &type, &flags);

        shape.sx  = PAR[PM_PAR_SXX];
        shape.sy  = PAR[PM_PAR_SYY];
        shape.sxy = PAR[PM_PAR_SXY];
        axes = psEllipseShapeToAxes (shape, 20.0);

        psLineInit (line);
        psLineAdd (line, "%5.2f",  0.0); // should be type
        psLineAdd (line, "%11.3f", PAR[PM_PAR_XPOS]);
        psLineAdd (line, "%11.3f", PAR[PM_PAR_YPOS]);
        psLineAdd (line, "%9.4f",  source->psfMag);
        psLineAdd (line, "%9.4f",  source->errMag);
        psLineAdd (line, "%13.4f", source->sky);
        psLineAdd (line, "%9.2f",  axes.major);
        psLineAdd (line, "%9.2f",  axes.minor);
        psLineAdd (line, "%6.1f",  axes.theta);
        psLineAdd (line, "%9.4f",  source->extMag);
        psLineAdd (line, "%9.4f",  source->apMag);
        psLineAdd (line, "%4d\n",  0); // should be flags
        fwrite (line->line, 1, line->Nline, f);
    }
    fclose (f);
    psFree (line);
    return true;
}

// XXX need to fix the FWHM / shape stuff,
// XXX make sure we are using the correct mags, etc
