// pstampdump  - read a fits table describing a postage stamp request or response file and
//               print the contents to stdout
//
//              Actually should work for any kind of fits table, but I'm not sure what will
//              happen for binary data.

#include <pslib.h>
#include <psmodules.h>
#include <string.h>

static psArray *readRequestTable(psString fileName)
{
    psFits *fitsFile = psFitsOpen(fileName, "r");
    if (fitsFile == NULL) {
        psError(PS_ERR_IO, false, "failed to open %s for output", fileName);
        return NULL;
    }

    psArray *array = psFitsReadTable(fitsFile);

    psFitsClose(fitsFile);

    if (array == NULL) {
        psError(PS_ERR_IO, false, "psFitsReadTable failed for %s", fileName);
        return NULL;
    } 

    return array;
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s filename\n", argv[0]);
        return 1;
    }

    psString fileName = argv[1];

    psArray *array = readRequestTable(fileName);
    if (array == NULL) {
        psErrorStackPrint(stderr, "failed to read fits table: %s\n", fileName);
        return 1;
    }

    if (!psArrayLength(array)) {
        fprintf(stderr, "%s is an empty table\n", fileName);
        exit(1);
    }

//    printf("FITS_TABLE METADATA\n");
    for (int i=0; i<psArrayLength(array); i++) {
        printf("ROW_%d METADATA\n", i);
        // psMetadataPrint(stderr, array->data[i], 0);
        // psMetadataConfigWrite(array->data[i], "-");
        psString str = psMetadataConfigFormat(array->data[i]);
        if (!str) {
            psErrorStackPrint(stderr, "Can't write to STDOUT\n");
            exit(PS_EXIT_SYS_ERROR);
        }
        printf(str);
        printf("END\n");
    }
//   printf("END\n");

    return 0;
}
