// 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;
}

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

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