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

#include <stdio.h>
#include <math.h>
#include <string.h>
#include "pslib.h"
#include "psAdditionals.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"

// translations between psphot object types and dophot object types
int pmSourceDophotType (pmSource *source)
{

    switch (source->type) {

    case PM_SOURCE_TYPE_DEFECT:
    case PM_SOURCE_TYPE_SATURATED:
        return (8);

    case PM_SOURCE_TYPE_STAR:
        if (source->mode & PM_SOURCE_MODE_SATSTAR)
            return (10);
        if (source->mode & PM_SOURCE_MODE_POOR)
            return (7);
        if (source->mode & PM_SOURCE_MODE_FAIL)
            return (4);
        return (1);

    case PM_SOURCE_TYPE_EXTENDED:
        return (2);

    default:
        return (0);
    }
    return (0);
}

// Given a FITS file pointer, read the table of object data
bool pmFPAviewWriteObjects (const pmFPAview *view, pmFPAfile *file)
{

    pmFPA *fpa = file->fpa;

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

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

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

    if (view->cell >= chip->cells->n) {
        return false;
    }
    pmCell *cell = chip->cells->data[view->cell];

    if (view->readout == -1) {
        pmCellWriteObjects (cell, view, file);
        return true;
    }

    if (view->readout >= cell->readouts->n) {
        return false;
    }
    pmReadout *readout = cell->readouts->data[view->readout];

    pmReadoutWriteObjects (readout, view, file);
    return true;
}

// read in all chip-level Objects files for this FPA
bool pmFPAWriteObjects (pmFPA *fpa, const pmFPAview *view, pmFPAfile *file)
{

    for (int i = 0; i < fpa->chips->n; i++) {

        pmChip *chip = fpa->chips->data[i];
        pmChipWriteObjects (chip, view, file);
    }
    return true;
}

// read in all cell-level Objects files for this chip
bool pmChipWriteObjects (pmChip *chip, const pmFPAview *view, pmFPAfile *file)
{

    for (int i = 0; i < chip->cells->n; i++) {

        pmCell *cell = chip->cells->data[i];
        pmCellWriteObjects (cell, view, file);
    }
    return true;
}

// read in all readout-level Objects files for this cell
bool pmCellWriteObjects (pmCell *cell, const pmFPAview *view, pmFPAfile *file)
{

    for (int i = 0; i < cell->readouts->n; i++) {

        pmReadout *readout = cell->readouts->data[i];
        pmReadoutWriteObjects (readout, view, file);
    }
    return true;
}

// read in all readout-level Objects files for this cell
bool pmReadoutWriteObjects (pmReadout *readout, const pmFPAview *view, pmFPAfile *file)
{

    bool status;
    char *filename;
    char *dataname;
    char *headname;
    pmHDU *hdu;
    pmHDU *phu;
    psMetadata *updates;
    psMetadata *outhead;

    psArray *sources = psMetadataLookupPtr (&status, readout->analysis, "PSPHOT.SOURCES");

    switch (file->type) {
    case PM_FPA_FILE_RAW:
        filename = pmFPAfileNameFromRule (file->filerule, file, view);
        pmSourcesWriteRAW (sources, filename);
        psFree (filename);
        break;

    case PM_FPA_FILE_OBJ:
        filename = pmFPAfileNameFromRule (file->filerule, file, view);
        pmSourcesWriteOBJ (sources, filename);
        psFree (filename);
        break;

    case PM_FPA_FILE_SX:
        filename = pmFPAfileNameFromRule (file->filerule, file, view);
        pmSourcesWriteSX (sources, filename);
        psFree (filename);
        break;

    case PM_FPA_FILE_CMP:
        // a SPLIT format : only one header and object table per file
        hdu = pmFPAviewThisHDU (view, file->fpa);
        filename = pmFPAfileNameFromRule (file->filerule, file, view);

        // copy the header to an output header, add the output header data
        outhead = psMetadataCopy (NULL, hdu->header);

        // check/fix first line (must be SIMPLE = F)
        psMetadataItem *item = psMetadataGet (outhead, PS_LIST_HEAD);
        if (strcmp (item->name, "SIMPLE") && strcmp (item->name, "XTENSION")) {
            psErrorStackPrint(stderr, "invalid header: first line is neither SIMPLE nor XTENSION\n");
            exit(EXIT_FAILURE);
        }
        if (!strcmp (item->name, "XTENSION")) {
            psMetadataRemoveIndex (outhead, PS_LIST_HEAD);
        }
        psMetadataAddBool (outhead, PS_LIST_HEAD, "SIMPLE", PS_META_REPLACE, "CMP file, not simple", false);

        // copy over the entries saved in the
        updates = psMetadataLookupPtr (&status, readout->analysis, "PSPHOT.HEADER");
        psMetadataCopy (outhead, updates);

        pmSourcesWriteCMP (sources, filename, outhead);
        psFree (outhead);
        psFree (filename);
        break;

    case PM_FPA_FILE_CMF:
        // write a PHU?
        // write a header?
        // write the data

        // get the current header
        hdu = pmFPAviewThisHDU (view, file->fpa);

        // if file does not yet have a PHU, write it to disk
        if (file->phu == NULL) {
            // get the corresponding phu
            phu = pmFPAviewThisPHU (view, file->fpa);

            // CMF always has extensions
            outhead = psMetadataCopy (NULL, phu->header);
            psMetadataAdd (outhead, PS_LIST_TAIL, "EXTEND", PS_DATA_BOOL | PS_META_REPLACE, "this file has extensions", true);
            psFitsWriteHeaderNotImage (file->fits, outhead);
            file->phu = phu->header;
            psTrace ("pmFPAfile", 5, "wrote phu %s (type: %d)\n", file->filename, file->type);
            psFree (outhead);
        }

        // this this header block is new, write it to disk,
        if (hdu->header != file->header) {
            // determine name for header extension
            headname = pmFPAfileNameFromRule (file->extxtra, file, view);
            outhead = psMetadataCopy (NULL, hdu->header);
            psMetadataAddStr (outhead, PS_LIST_TAIL, "EXTNAME", PS_META_REPLACE, "extension name", headname);
            psFitsWriteHeaderNotImage (file->fits, outhead);
            psTrace ("pmFPAfile", 5, "wrote ext head %s (type: %d)\n", file->filename, file->type);
            file->header = hdu->header;
            psFree (outhead);
            psFree (headname);
        }

        // write this table to disk
        dataname = pmFPAfileNameFromRule (file->extrule, file, view);
        updates = psMetadataLookupPtr (&status, readout->analysis, "PSPHOT.HEADER");
        pmSourcesWriteCMF (file->fits, sources, updates, dataname);
        psTrace ("pmFPAfile", 5, "wrote ext data %s (type: %d)\n", file->filename, file->type);
        psFree (dataname);
        break;

    default:
        fprintf (stderr, "warning: type mismatch\n");
        break;
    }
    return true;
}
// a MEF CMF file has: PHU, CELL-HEAD, TABLE, CELL-HEAD, TABLE, TABLE, TABLE...

// Given a FITS file pointer, read the table of object data
bool pmFPAviewReadObjects (const pmFPAview *view, pmFPAfile *file)
{
    pmFPA *fpa = file->fpa;

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

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

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

    if (view->cell >= chip->cells->n) {
        return false;
    }
    pmCell *cell = chip->cells->data[view->cell];

    if (view->readout == -1) {
        pmCellReadObjects (cell, view, file);
        return true;
    }

    if (view->readout >= cell->readouts->n) {
        return false;
    }
    pmReadout *readout = cell->readouts->data[view->readout];

    pmReadoutReadObjects (readout, view, file);
    return true;
}

// read in all chip-level Objects files for this FPA
bool pmFPAReadObjects (pmFPA *fpa, const pmFPAview *view, pmFPAfile *file)
{

    for (int i = 0; i < fpa->chips->n; i++) {

        pmChip *chip = fpa->chips->data[i];
        pmChipReadObjects (chip, view, file);
    }
    return true;
}

// read in all cell-level Objects files for this chip
bool pmChipReadObjects (pmChip *chip, const pmFPAview *view, pmFPAfile *file)
{

    for (int i = 0; i < chip->cells->n; i++) {

        pmCell *cell = chip->cells->data[i];
        pmCellReadObjects (cell, view, file);
    }
    return true;
}

// read in all readout-level Objects files for this cell
bool pmCellReadObjects (pmCell *cell, const pmFPAview *view, pmFPAfile *file)
{

    for (int i = 0; i < cell->readouts->n; i++) {

        pmReadout *readout = cell->readouts->data[i];
        pmReadoutReadObjects (readout, view, file);
    }
    return true;
}

// read in all readout-level Objects files for this cell
bool pmReadoutReadObjects (pmReadout *readout, const pmFPAview *view, pmFPAfile *file)
{

    bool status;
    psArray *sources = NULL;
    pmHDU *hdu;

    switch (file->type) {
    case PM_FPA_FILE_OBJ:
        fprintf (stderr, "warning: OBJ is not supported as an input object format\n");
        break;

    case PM_FPA_FILE_SX:
        fprintf (stderr, "warning: SX is not supported as an input object format\n");
        break;

    case PM_FPA_FILE_CMP:
        // a SPLIT format : only one header and object table per file

        // read in header, if not yet loaded
        hdu = pmFPAviewThisHDU (view, file->fpa);

        char *filename = pmFPAfileNameFromRule (file->filerule, file, view);
        file->fits = psFitsOpen (filename, "r");
        hdu->header = psFitsReadHeader (NULL, file->fits);
        psFitsClose (file->fits);
        sources  = pmSourcesReadCMP (filename, hdu->header);
        psFree (filename);
        break;

    case PM_FPA_FILE_CMF:
        // read in header, if not yet loaded
        hdu = pmFPAviewThisHDU (view, file->fpa);
        if (hdu->header == NULL) {
            char *headname = pmFPAfileNameFromRule (file->extxtra, file, view);
            psFitsMoveExtName (file->fits, headname);
            hdu->header = psFitsReadHeader (NULL, file->fits);
            psFree (headname);
        }

        char *dataname = pmFPAfileNameFromRule (file->extrule, file, view);
        psFitsMoveExtName (file->fits, dataname);
        sources  = pmSourcesReadCMF (file->fits, hdu->header);
        psFree (dataname);
        break;

    default:
        fprintf (stderr, "warning: type mismatch\n");
        break;
    }
    status = psMetadataAdd (readout->analysis, PS_LIST_TAIL, "PSPHOT.SOURCES", PS_DATA_ARRAY, "psphot sources", sources);
    return true;
}


