/** @file  pmSourceIO.c
 *
 *  @author EAM, IfA
 *
 *  @version $Revision: 1.1.2.5 $ $Name: not supported by cvs2svn $
 *  @date $Date: 2006-04-14 21:43:59 $
 *
 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
 *
 */

#include <stdio.h>
#include <math.h>
#include <string.h>
#include "pslib.h"
#include "psLine.h"
#include "psEllipse.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[4];
        shape.sy  = PAR[5];
        shape.sxy = PAR[6];
        axes = psEllipseShapeToAxes (shape);

        psLineInit (line);
        psLineAdd (line, "%5.2f",  0.0); // should be type
        psLineAdd (line, "%11.3f", PAR[2]);
        psLineAdd (line, "%11.3f", PAR[3]);
        psLineAdd (line, "%9.4f",  source->psfMag);
        psLineAdd (line, "%9.4f",  source->errMag);
        psLineAdd (line, "%13.4f", PAR[0]);
        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
