#include <stdio.h>
#include "pslib.h"
#include "papmodule.h"
#include "papFocalPlane.h"

psMemoryId memPrint(const psMemBlock *ptr)
{
    fprintf(stderr, "File: %s\n", ptr->file);
    fprintf(stderr, "Memory block %qd:\n"
	    "\tFile %s, line %d, size %d\n"
	    "\tRefCounter: %qd\n"
	    "\tPosts: %x %x %x\n",
	    ptr->id, ptr->file, ptr->lineno, ptr->userMemorySize, ptr->refCounter,
	    ptr->startblock, ptr->endblock, *(psPtr *)((int8_t *) (ptr + 1) + ptr->userMemorySize));
    return 0;
}
 
int main(int argc, char *argv[])
{
#if 0
    psMemAllocateCallbackSet(memPrint);
    psMemAllocateCallbackSetID(921);
    psMemFreeCallbackSet(memPrint);
    psMemFreeCallbackSetID(921);
#endif

    (void)psTraceSetLevel(".", 10);
    (void)psTraceSetLevel("readExtension", 10);
    (void)psTraceSetLevel("readMultipleRegions", 0);
    (void)psTraceSetLevel("portions", 0);
    (void)psTraceSetLevel("pmFPAPrint", 10);
    (void)psTraceSetLevel("pmFPAfromHeader", 10);
    (void)psTraceSetLevel("pmCameraFromHeader", 10);



    if (argc != 3) {
	printf("Usage: %s IPP_CONFIG IMAGE\n", argv[0]);
	exit(EXIT_FAILURE);
    }
    const char *ipprcName = argv[1];
    const char *imageName = argv[2];

    int badLines = 0;			// Number of bad lines in camera configuration
    psMetadata *ipprc = psMetadataConfigParse(NULL, &badLines, ipprcName, true); // Read IPP config file
    if (badLines > 0) {
	psLogMsg(__func__, PS_LOG_WARN, "%d bad lines encountered while reading IPP configuration %s\n",
		 badLines, ipprcName);
    }

    psFits *fits = psFitsAlloc(imageName);
    psMetadata *header = psFitsReadHeader(NULL, fits);

    psMetadata *camera = pmCameraFromHeader(header, ipprc);

    papFPA *fpa = pmFPAConstruct(camera, NULL);

    (void)pmFPARead(fpa, fits);
    (void)pmFPAPrint(fpa);

#if 0
    psMetadata *newCamera = psMetadataConfigParse(NULL, &badLines, "megacam_splice.config", true);
    papFPA *newfpa = pmFPAConstruct(newCamera, NULL);
    pmFPAMorph(newfpa, fpa);
    psFits *newfits = psFitsAlloc("test.fits");
    pmFPAWrite(fits, fpa);
    psFree(newfits);
    psFree(newfpa);
    psFree(newCamera);
#endif

    // Tidy up
    psMemCheckCorruption(true);

    psFree(camera);
    psFree(fits);

    psFree(fpa);

    return 0;
}
