#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

#include "ppStack.h"

#define TIMER_NAME "PPSTACK"            // Name of timer

int main(int argc, char *argv[])
{
    psExit exitValue = PS_EXIT_SUCCESS; // Exit value
    psTimerStart(TIMER_NAME);
    psLibInit(NULL);

    pmConfig *config = pmConfigRead(&argc, argv, PPSTACK_RECIPE); // Configuration
    if (!config) {
        psErrorStackPrint(stderr, "Error reading configuration.");
        exitValue = PS_EXIT_CONFIG_ERROR;
        goto die;
    }

    (void) psTraceSetLevel("ppStack", 5);

    if (!ppStackArgumentsSetup(argc, argv, config)) {
        psErrorStackPrint(stderr, "Error reading arguments.\n");
        exitValue = PS_EXIT_CONFIG_ERROR;
        goto die;
    }

    if (!pmModelClassInit()) {
        psErrorStackPrint(stderr, "Error initialising model classes.\n");
        exitValue = PS_EXIT_PROG_ERROR;
        goto die;
    }

    if (!psphotInit()) {
        psErrorStackPrint(stderr, "Error initialising psphot.\n");
        exitValue = PS_EXIT_PROG_ERROR;
        goto die;
    }

    if (!ppStackCamera(config)) {
        psErrorStackPrint(stderr, "Error setting up input files.\n");
        exitValue = PS_EXIT_CONFIG_ERROR;
        goto die;
    }

    if (!ppStackArgumentsParse(config)) {
        psErrorStackPrint(stderr, "Error reading arguments.\n");
        exitValue = PS_EXIT_CONFIG_ERROR;
        goto die;
    }

    if (!ppStackLoop(config)) {
        psErrorStackPrint(stderr, "Error performing combination.\n");
        exitValue = PS_EXIT_DATA_ERROR;
        goto die;
    }


     // Common code for the death.
die:
    psTrace("ppStack", 1, "Finished at %f sec\n", psTimerMark(TIMER_NAME));
    psTimerStop();

    psFree(config);
    pmModelClassCleanup();
    pmConfigDone();
    psLibFinalize();

    exit(exitValue);
}

