/** @file ppSub.c
 *
 *  @brief
 *
 *  @ingroup ppSub
 *
 *  @author IfA
 *  @version $Revision: 1.12 $ $Name: not supported by cvs2svn $
 *  @date $Date: 2009-02-18 00:31:20 $
 *  Copyright 2009 Institute for Astronomy, University of Hawaii
 */

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

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

#include "ppSub.h"

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

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

    ppSubVersionPrint();

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

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

    data = ppSubDataAlloc(config);

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

    if (!ppSubCamera(data)) {
        psErrorStackPrint(stderr, "Error setting up camera.\n");
        exitValue = PS_EXIT_CONFIG_ERROR;
        goto die;
    }

    if (!ppSubLoop(data)) {
        psErrorStackPrint(stderr, "Error performing subtraction.\n");
        exitValue = PS_EXIT_SYS_ERROR;
        goto die;
    }

 die:
    psTrace("ppSub", 1, "Finished at %f sec\n", psTimerMark("ppSub"));
    psTimerStop();

    psFree(data);

    pmVisualClose(); //close plot windows, if -visual is set
    pmModelClassCleanup();
    pmConfigDone();
    psLibFinalize();

    exit(exitValue);
}
