# include <stdio.h>
# include <strings.h>
# include <math.h>
# include "pslib.h"

int main (int argc, char **argv) {

    if (argc != 3) {
        fprintf (stderr, "USAGE: icd-demo (input) (output)\n");
        exit (2);
    }

    // construct a sample FITS table based on the given descriptive metadata file
    psFits *fits = psFitsOpen (argv[2], "w");

    {
        psMetadata *header  = psMetadataAlloc ();
        psMetadataAddStr (header, PS_LIST_HEAD, "EXTID", 0, "", "blank");
        psFitsWriteBlank (fits, header, "blank");
    }

    {
        psMetadata *header  = psMetadataAlloc ();
        psMetadataAddStr (header, PS_LIST_HEAD, "EXTID", 0, "", "blank1");
        psFitsWriteBlank (fits, header, "blank1");
    }

    {
        psMetadata *header  = psMetadataAlloc ();
        psMetadataAddStr (header, PS_LIST_HEAD, "EXTID", 0, "", "table1");

        psArray *table = psArrayAllocEmpty (100);
        for (int i = 0; i < 10; i++) {

            psMetadata *row = psMetadataAlloc ();
            psMetadataAdd (row, PS_LIST_TAIL, "N", PS_DATA_S16, "", i);
            psMetadataAdd (row, PS_LIST_TAIL, "F", PS_DATA_F32, "", i*0.2);
            psMetadataAdd (row, PS_LIST_TAIL, "G", PS_DATA_F32, "", i*0.5);
            psArrayAdd (table, 100, row);
            psFree (row);
        }

        psFitsInsertTable (fits, header, table, "table1", true);
    }

    {
        psMetadata *header  = psMetadataAlloc ();
        psMetadataAddStr (header, PS_LIST_HEAD, "EXTID", 0, "", "blank2");
        psFitsWriteBlank (fits, header, "blank2");
    }

    {
        psMetadata *header  = psMetadataAlloc ();
        psMetadataAddStr (header, PS_LIST_HEAD, "EXTID", 0, "", "table2");

        psArray *table = psArrayAllocEmpty (100);
        for (int i = 0; i < 10; i++) {

            psMetadata *row = psMetadataAlloc ();
            psMetadataAdd (row, PS_LIST_TAIL, "N", PS_DATA_S16, "", i);
            psMetadataAdd (row, PS_LIST_TAIL, "F", PS_DATA_F32, "", i*0.2);
            psMetadataAdd (row, PS_LIST_TAIL, "G", PS_DATA_F32, "", i*0.5);
            psArrayAdd (table, 100, row);
            psFree (row);
        }

        psFitsInsertTable (fits, header, table, "table2", true);
    }

    psFitsClose (fits);
}
