#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(&argc, argv, 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 (argc == 2) {
        outName = argv[1];
        psString resolved = pmConfigConvertFilename(outName, config, true); // Resolved filename

        if (outName && strlen(outName) > 0) {
            outFile = fopen(outName, "w");
            if (!outFile) {
                psLogMsg("ppStats", PS_LOG_ERROR, "Unable to open output file %s\n", resolved);
                psFree(resolved);
                // 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 %s.\n", resolved);
            psFree(resolved);
            status = PS_EXIT_CONFIG_ERROR;
            goto die;
        }
        psFree(resolved);
    }

    // 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;
    }

    if (data->fileLevel) {
        const char *level = pmFPALevelToName(pmFPAPHULevel(config->format)); // Level for file
        psMetadataAddStr(results, PS_LIST_HEAD, "FILE.LEVEL", 0, "File level", level);
    }

    // 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;
}
