/** @file  pmSourceIO.c
 *
 *  @author EAM, IfA
 *
 *  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
 *  @date $Date: 2006-09-30 02:29:59 $
 *
 *  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"

// 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, write the table of object data
bool pmFPAviewWriteObjects (const pmFPAview *view, pmFPAfile *file)
{

    pmFPA *fpa = file->fpa;

    if (view->chip == -1) {
        if (!pmFPAWriteObjects (fpa, view, file)) {
            psError(PS_ERR_IO, false, "Failed to write objects from fpa");
            return false;
        }
        return true;
    }

    if (view->chip >= fpa->chips->n) {
        psError(PS_ERR_UNKNOWN, false, "Writing chip == %d (>= chips->n == %ld)", view->chip, fpa->chips->n);
        return false;
    }
    pmChip *chip = fpa->chips->data[view->chip];

    if (view->cell == -1) {
        if (!pmChipWriteObjects (chip, view, file)) {
            psError(PS_ERR_IO, false, "Failed to write objects from chip");
            return false;
        }
        return true;
    }

    if (view->cell >= chip->cells->n) {
        psError(PS_ERR_UNKNOWN, false, "Writing cell == %d (>= cells->n == %ld)",
                view->cell, chip->cells->n);
        return false;
    }
    pmCell *cell = chip->cells->data[view->cell];

    if (view->readout == -1) {
        if (!pmCellWriteObjects (cell, view, file)) {
            psError(PS_ERR_IO, false, "Failed to write objects from cell");
            return false;
        }

        return true;
    }

    if (view->readout >= cell->readouts->n) {
        psError(PS_ERR_UNKNOWN, false, "Writing readout == %d (>= readouts->n == %ld)",
                view->readout, cell->readouts->n);
        return false;
    }
    pmReadout *readout = cell->readouts->data[view->readout];

    if (!pmReadoutWriteObjects (readout, view, file)) {
        psError(PS_ERR_IO, false, "Failed to write objects from readout %d", view->readout);
        return false;
    }

    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];
        if (!pmChipWriteObjects (chip, view, file)) {
            psError(PS_ERR_IO, false, "Failed to write %dth chip", i);
            return false;
        }
    }
    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];
        if (!pmCellWriteObjects (cell, view, file)) {
            psError(PS_ERR_IO, false, "Failed to write %dth cell", i);
            return false;
        }
    }
    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];
        if (!pmReadoutWriteObjects (readout, view, file)) {
            psError(PS_ERR_IO, false, "Failed to write %dth readout", i);
            return false;
        }
    }
    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");
    if (sources == NULL)
        return false;

    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);

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

        bool status = pmSourcesWriteCMP (sources, filename, outhead);
        psFree (outhead);
        psFree (filename);

        if (!status) {
            psError(PS_ERR_IO, false, "Failed to write CMP file\n");
            return false;
        }
        break;

    case PM_FPA_FILE_CMF:
        // 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
        if (file->phu == NULL) {
            // get the corresponding phu
            phu = pmFPAviewThisPHU (view, file->fpa);

            // if there is no PHU, this is a single header+image (extension-less) file
            // if there is a PHU, write it out as a 'blank'
            if (phu) {
                outhead = psMetadataCopy (NULL, phu->header);
                psMetadataAddBool (outhead, PS_LIST_TAIL, "EXTEND", PS_META_REPLACE, "this file has extensions", true);
                // XXX what is the EXTNAME??
                psFitsWriteBlank (file->fits, outhead, "");
                file->phu = phu->header;
                psTrace ("pmFPAfile", 5, "wrote phu %s (type: %d)\n", file->filename, file->type);
                psFree (outhead);
            }
        }

        // 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);
            if (file->phu == NULL) {
                // this hdu->header acts as the PHU: set EXTEND to be true
                psMetadataAddBool (outhead, PS_LIST_TAIL, "EXTEND", PS_META_REPLACE, "this file has extensions", true);
            }

            // XXX : see note below about DVO/addstar expectations
            updates = psMetadataLookupPtr (&status, readout->analysis, "PSPHOT.HEADER");
            psMetadataCopy (outhead, updates);

            psFitsWriteBlank (file->fits, outhead, headname);
            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);

        // XXX : currently, this is being added to the TABLE header
        //       this may be the correct location for a MEF file, but it is
        //       inconsistent with DVO/addstar expectations.  DVO/addstar
        //       currently only expects a single header/table pair, and the
        //       metadata are in the blank (image) header, not the table header
        //       it may be necessary to put the results from the first readout
        //       in the blank image header to cover this case.
        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)
{
    // determine the number of readouts:
    switch (file->type) {
    case PM_FPA_FILE_CMP: {
            pmReadout *readout;
            readout = pmReadoutAlloc (cell);
            psFree (readout);
            break;
        }
    default:
        psAbort ("pmSourceIO", "n readouts is not yet defined\n");
    }
    for (int i = 0; i < cell->readouts->n; i++) {
        pmReadout *readout = cell->readouts->data[i];
        pmReadoutReadObjects (readout, view, file);
        cell->data_exists = true;
    }
    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);
        if (file->filename)
            psFree (file->filename);
        file->filename = pmFPAfileNameFromRule (file->filerule, file, view);

        // indirect filenames
        if (!strcasecmp (file->filename, "@FILES")) {
            psFree (file->filename);
            char *extra = pmFPAfileNameFromRule (file->filextra, file, view);
            file->filename = psMetadataLookupStr (&status, file->names, extra);
            psFree (extra);
            if (file->filename == NULL)
                return false;
            // psMetadataLookupStr just returns a view, file->filename must be protected
            psMemIncrRefCounter (file->filename);
        }
        file->fits = psFitsOpen (file->filename, "r");
        if (hdu->header != NULL) {
            psFree (hdu->header);
        }
        hdu->header = psFitsReadHeader (NULL, file->fits);
        psFitsClose (file->fits);
        file->fits = NULL;

        sources = pmSourcesReadCMP (file->filename, hdu->header);
        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;
    }
    readout->data_exists = true;
    status = psMetadataAdd (readout->analysis, PS_LIST_TAIL, "PSPHOT.SOURCES", PS_DATA_ARRAY, "psphot sources", sources);
    psFree (sources);
    return true;
}


