# include "psphotInternal.h"

void psExit (int status, char *process, char *format, ...) {

    va_list ap;

    va_start (ap, format);
    fprintf (stderr, "exiting %s\n", process);
    vfprintf (stderr, format, ap);
    va_end (ap);

    exit (status);
}

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

    psRegion region = {0,0,0,0};        // a region representing the entire array
    psphotTestArguments (&argc, argv);

    psFits *file = psFitsOpen (argv[1], "r");
    psMetadata *header = psFitsReadHeader (NULL, file);
    psImage *image = psFitsReadImage (NULL, file, region, 0);
    psFitsClose (file);

    psImageJpegColormap (argv[5]);

    // psImage *fimage = psImageCopy (NULL, image, PS_TYPE_F32);

    int binning = atof(argv[6]);

    psStats *stats = psStatsAlloc (PS_STAT_SAMPLE_MEAN);
    psImage *fimage = psImageRebin (NULL, image, NULL, 0, binning, stats);

    float min = atof(argv[3]);
    float max = atof(argv[4]);

    psImageJpeg (fimage, argv[2], min, max);

    psFree (header);
    psFree (image);
    exit (0);
}


# if (0)

    psMetadata *row;
    psArray *table;

    psMetadataItem *mdi;

    psMetadataConfigWrite (header, argv[2]);

    // attempt to write image with NAXIS = 0
    mdi = psMetadataLookup (header, "NAXIS");
    mdi->data.S32 = 0;
    mdi->type = PS_DATA_S32;

    // create a test image
    // psImage *tmpimage = psImageAlloc (10, 10, PS_DATA_F32);

    // create a test table
    table = psArrayAllocEmpty (10);

    for (int i = 0; i < 10; i++) {
        row = psMetadataAlloc ();
        psMetadataAdd (row, PS_LIST_TAIL, "ROW",   PS_DATA_S32,    "", i);
        psMetadataAdd (row, PS_LIST_TAIL, "FROW",  PS_TYPE_F32,    "", 0.1*i);
        psMetadataAdd (row, PS_LIST_TAIL, "DUMMY", PS_DATA_STRING, "", "test line");

        table->data[i] = row;
    }
    table->n = 10;

    psMetadata *theader = psMetadataAlloc ();
    psMetadataAdd (theader, PS_LIST_HEAD, "EXTNAME", PS_DATA_STRING, "extension name", "SMPFILE");

    psFits *fits = psFitsOpen (argv[3], "w");
    // psFitsWriteImage (fits, header, tmpimage, 0);
    psFitsWriteHeader (header, fits);
    psFitsWriteTable (fits, theader, table);

# endif
