#include <stdio.h>
#include <assert.h>
#include <pslib.h>
#include <psmodules.h>

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

    if (argc < 4) {
        fprintf (stderr, "USAGE: dumpvideo (input) (extname) (output) [-includetable]\n");
	exit (2);
    }

    pmConfig *config = pmConfigRead(&argc, argv, NULL);
    if (config == NULL) {
        psErrorStackPrint(stderr, "Can't find site configuration!\n");
        exit(EXIT_FAILURE);
    }



    char *input   = argv[1];      // Input file name
    char *extname = argv[2];      // Extension of interest
    char *output  = argv[3];      // Output file name

    bool includetable = false;
    if (argc > 4) {
        includetable = true;
    }

    psString inputResolved = pmConfigConvertFilename(input, config, false, false);
    psFits *infile = psFitsOpen (inputResolved, "r"); // Input file
    if (!infile) {
        fprintf (stderr, "Unable to open input file %s", input);
        exit (PS_EXIT_DATA_ERROR);
    }

    psString outputResolved = pmConfigConvertFilename(output, config, true, true);
    psFits *outfile = psFitsOpen (outputResolved, "w"); // Output file
    if (!outfile) {
        fprintf (stderr, "Unable to open output file %s", output);
        exit(PS_EXIT_DATA_ERROR);
    }

    if (!psFitsMoveExtName (infile, extname)) {
        fprintf (stderr, "Unable to find extname %s\n", extname);
        exit(PS_EXIT_DATA_ERROR);
    }

    psMetadata *header = psFitsReadHeader (NULL, infile);

    psRegion region = {0, 0, 0, 0};
    psArray *cube = psFitsReadImageCube (infile, region);

    psFitsWriteImageCube (outfile, header, cube, extname);

    if (includetable) {
        psString video_extname = NULL;
        psStringAppend(&video_extname, "video_table_%s", extname);
        if (!psFitsMoveExtName (infile, video_extname)) {
            fprintf (stderr, "Unable to find extname %s\n", video_extname);
            exit(PS_EXIT_DATA_ERROR);
        }
        psArray *table = psFitsReadTable(infile);
        if (!psFitsWriteTable(outfile, NULL, table, video_extname)) {
            fprintf (stderr, "Unable to write video table video_extname %s\n", video_extname);
            exit(PS_EXIT_DATA_ERROR);
        }
    }

    psFitsClose(infile);
    psFitsClose(outfile);

    return PS_EXIT_SUCCESS;
}
    
