/** @file  pmSourceIO.c
 *
 *  @author EAM, IfA
 *
 *  @version $Revision: 1.1.2.4 $ $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"

// dophot-style output list with fixed line width
bool pmSourcesWriteOBJ (psArray *sources, char *filename)
{

    int type;
    psF32 *PAR, *dPAR;
    float dmag, apResid;
    psEllipseShape shape;
    psEllipseAxes axes;

    psTimerStart ("string");

    psLine *line = psLineAlloc (104);  // 104 is dophot-defined 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;

        dmag = dPAR[1] / PAR[1];
        type = pmSourceDophotType (source);
        if ((source->apMag < 99.0) && (source->psfMag < 99.0)) {
            apResid = source->apMag - source->psfMag;
        } else {
            apResid = 0.0;
        }

        shape.sx  = PAR[4];
        shape.sy  = PAR[5];
        shape.sxy = PAR[6];
        axes = psEllipseShapeToAxes (shape);

        psLineInit (line);
        psLineAdd (line, "%3d",   type);
        psLineAdd (line, "%8.2f", PAR[2]);
        psLineAdd (line, "%8.2f", PAR[3]);
        psLineAdd (line, "%8.3f", source->psfMag);
        psLineAdd (line, "%6.3f", dmag);
        psLineAdd (line, "%9.2f", PAR[0]);
        psLineAdd (line, "%9.3f", axes.major);
        psLineAdd (line, "%9.3f", axes.minor);
        psLineAdd (line, "%7.2f", axes.theta);
        psLineAdd (line, "%8.3f", source->extMag);
        psLineAdd (line, "%8.3f", source->apMag);
        psLineAdd (line, "%8.2f\n", apResid);
        fwrite (line->line, 1, line->Nline, f);
    }
    fclose (f);
    psFree (line);
    fprintf (stderr, "%f seconds for %d objects\n", psTimerMark ("string"), (int)sources->n);
    return true;
}
