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

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

#define TIMERNAME "PPSTATS"

#include "ppStats.h"
#include "ppStatsSetupFromArgs.h"

int main(int argc, char *argv[])
{
    psExit status = PS_EXIT_SUCCESS;

    psLibInit(NULL);
    psTimerStart(TIMERNAME);

    // Parse the configuration and arguments
    pmConfig *config = pmConfigRead(&argc, argv, PPSTATS_RECIPE);
    if (!config) {
        psError(PS_ERR_UNKNOWN, false, "Unable to read configuration.\n");
        exit(PS_EXIT_CONFIG_ERROR);
    }

    // Get the options, open the files
    ppStatsData *data = ppStatsSetupFromArgs(config);
    if (!data) {
        psError(PS_ERR_UNKNOWN, false, "Unable to parse command-line arguments.\n");
        exit(PS_EXIT_CONFIG_ERROR);
    }

    // Output filename is optional
    const char *outName = NULL;         // Output file name
    FILE *outFile = stdout;             // Output file
    if (*config->argc == 2) {
        outName = config->argv[1];
        if (outName && strlen(outName) > 0) {
            outFile = fopen(outName, "w");
            if (!outFile) {
                psLogMsg("ppStats", PS_LOG_ERROR, "Unable to open output file %s\n", outName);
		// XXX this could be a system or config error, but not a data error
                status = PS_EXIT_CONFIG_ERROR;
                goto die;
            }
        } else {
            psLogMsg("ppStats", PS_LOG_ERROR, "Unable to open output file.\n");
            status = PS_EXIT_CONFIG_ERROR;
            goto die;
        }
    }

    // Go through the FPA and do the hard work
    psMetadata *results = ppStatsLoop(NULL, data, config);
    if (psListLength(results->list) == 0) {
        psLogMsg("ppStats", PS_LOG_ERROR, "No output.\n");
        psFree(results);
        status = PS_EXIT_DATA_ERROR;
        goto die;
    }

    // Format and print the output
    psString output = psMetadataConfigFormat(results);
    if (!output) {
        psLogMsg("ppStats", PS_LOG_ERROR, "Unable to generate configuration file with result.\n");
        psFree(results);
        status = PS_EXIT_CONFIG_ERROR;
        goto die;
    }
    fprintf(outFile, "%s", output);
    psFree(output);

    // Clean up
    psFree(results);
    if (outName) {
        fclose(outFile);
    }

    // Common code for the death.
die:
    if (status) {
	psErrorStackPrint (stderr, "failure in %s", __func__);
    }
    psFree(data);
    psFree(config);
    pmConceptsDone();
    pmConfigDone();
    psLibFinalize();

    return status;
}
