/*
 * stacktool.c
 *
 * Copyright (C) 2007-2008  Joshua Hoblitt
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * program; see the file COPYING. If not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ippdb.h>

#include "pxtools.h"
#include "stacktool.h"

static bool definebyqueryMode(pxConfig *config);
static bool definerunMode(pxConfig *config);
static bool updaterunMode(pxConfig *config);
static bool addinputskyfileMode(pxConfig *config);
static bool inputskyfileMode(pxConfig *config);
static bool tosumMode(pxConfig *config);
static bool addsumskyfileMode(pxConfig *config);
static bool sumskyfileMode(pxConfig *config);
static bool revertsumskyfileMode(pxConfig *config);

static bool setstackRunState(pxConfig *config, psS64 stack_id, const char *state);

# define MODECASE(caseName, func) \
    case caseName: \
    if (!func(config)) { \
        goto FAIL; \
    } \
    break;

int main(int argc, char **argv)
{
    psLibInit(NULL);

    pxConfig *config = stacktoolConfig(NULL, argc, argv);
    if (!config) {
        psError(PXTOOLS_ERR_CONFIG, false, "failed to configure");
        goto FAIL;
    }

    switch (config->mode) {
        MODECASE(STACKTOOL_MODE_DEFINEBYQUERY,              definebyqueryMode);
        MODECASE(STACKTOOL_MODE_DEFINERUN,          definerunMode);
        MODECASE(STACKTOOL_MODE_UPDATERUN,          updaterunMode);
        MODECASE(STACKTOOL_MODE_ADDINPUTSKYFILE,    addinputskyfileMode);
        MODECASE(STACKTOOL_MODE_INPUTSKYFILE,       inputskyfileMode);
        MODECASE(STACKTOOL_MODE_TOSUM,              tosumMode);
        MODECASE(STACKTOOL_MODE_ADDSUMSKYFILE,      addsumskyfileMode);
        MODECASE(STACKTOOL_MODE_SUMSKYFILE,         sumskyfileMode);
        MODECASE(STACKTOOL_MODE_REVERTSUMSKYFILE,   revertsumskyfileMode);
        default:
            psAbort("invalid option (this should not happen)");
    }

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

    exit(EXIT_SUCCESS);

FAIL:
    psErrorStackPrint(stderr, "\n");
    int exit_status = pxerrorGetExitStatus();

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

    exit(exit_status);
}


static bool definebyqueryMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    // required options
    PXOPT_LOOKUP_STR(workdir, config->args, "-workdir", true, false);

    psMetadata *whereRE = psMetadataAlloc(); // rawExp where
    psMetadata *whereWSF = psMetadataAlloc(); // warpSkyfile where
    // map -inst -> camera, etc
    PXOPT_COPY_STR(config->args, whereRE, "-select_inst", "camera", "==");
    PXOPT_COPY_STR(config->args, whereRE, "-select_telescope", "telescope", "==");
    PXOPT_COPY_STR(config->args, whereRE, "-select_filter", "filter", "==");
    PXOPT_COPY_STR(config->args, whereRE, "-select_uri", "uri", "==");
    PXOPT_COPY_TIME(config->args, whereRE, "-select_dateobs_begin", "dateobs", ">=");
    PXOPT_COPY_TIME(config->args, whereRE, "-select_dateobs_end", "dateobs", "<=");
    PXOPT_COPY_F32(config->args, whereRE, "-select_airmass_min", "airmass", ">=");
    PXOPT_COPY_F32(config->args, whereRE, "-select_airmass_max", "airmass", "<=");
    PXOPT_COPY_F32(config->args, whereRE, "-select_sat_pixel_frac_max", "sat_pixel_frac", "<=");
    PXOPT_COPY_F32(config->args, whereRE, "-select_exp_time_min", "exp_time", ">=");
    PXOPT_COPY_F32(config->args, whereRE, "-select_exp_time_max", "exp_time", "<=");
    PXOPT_COPY_F32(config->args, whereRE, "-select_ccd_temp_min", "ccd_temp", ">=");
    PXOPT_COPY_F32(config->args, whereRE, "-select_ccd_temp_max", "ccd_temp", "<=");
    PXOPT_COPY_F32(config->args, whereRE, "-select_posang_min", "posang", ">=");
    PXOPT_COPY_F32(config->args, whereRE, "-select_posang_max", "posang", "<=");
    PXOPT_COPY_F32(config->args, whereRE, "-select_solang_min", "solang", ">=");
    PXOPT_COPY_F32(config->args, whereRE, "-select_solang_max", "solang", "<=");
    PXOPT_COPY_STR(config->args, whereWSF, "-select_skycell_id", "skycell_id", "==");
    PXOPT_LOOKUP_BOOL(randomSubset, config->args, "-random_subset", false);
    PXOPT_LOOKUP_S32(randomLimit, config->args, "-random_limit", false, false);

    if (!psListLength(whereRE->list) && !psListLength(whereWSF->list) &&
        !psMetadataLookupBool(NULL, config->args, "-all")) {
        psFree(whereRE);
        psFree(whereWSF);
        psError(PXTOOLS_ERR_DATA, false, "search parameters are required");
        return false;
    }

    // default
    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);
    PXOPT_LOOKUP_TIME(registered, config->args, "-registered", false, false);
    PXOPT_COPY_STR(config->args, whereRE, "-select_exp_type", "exp_type", "==");
    PXOPT_COPY_F32(config->args, whereWSF, "-select_good_frac_min", "good_frac", ">=");

    psString query = pxDataGet("stacktool_find_complete_warps.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

    if (whereRE) {
        psString whereClause = psDBGenerateWhereConditionSQL(whereRE, "rawExp");
        psStringAppend(&query, " AND %s", whereClause);
        psFree(whereClause);
    }
    psFree(whereRE);

    if (whereWSF) {
        psString whereClause = psDBGenerateWhereConditionSQL(whereWSF, "warpSkyfile");
        psStringAppend(&query, " AND %s", whereClause);
        psFree(whereClause);
    }
    psFree(whereWSF);

    if (!p_psDBRunQuery(config->dbh, query)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }
    psFree(query);

    psArray *output = p_psDBFetchResult(config->dbh);
    if (!output) {
        psErrorCode err = psErrorCodeLast();
        switch (err) {
            case PS_ERR_DB_CLIENT:
                psError(PXTOOLS_ERR_SYS, false, "database error");
            case PS_ERR_DB_SERVER:
                psError(PXTOOLS_ERR_PROG, false, "database error");
            default:
                psError(PXTOOLS_ERR_PROG, false, "unknown error");
        }

        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("stacktool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    // valid_warpids should be NULL unless randomSubset is specified
    psVector *valid_warpids = NULL;
    if (randomSubset && (randomLimit < psArrayLength(output))) {
        // loop over the array of metadata and figure out which warp_id are in
        // the result set
        psArray *warps = psArrayAlloc(0);
        for (long i = 0; i < psArrayLength(output); i++) {
//            psMetadata *md = output->data[i];

            // pull out the warp_id
            bool status = false;
//            psS64 warp_id = psMetadataLookupS64(&status, md, "warp_id");
            if (!status) {
                psError(PS_ERR_UNKNOWN, false, "failed to lookup warp_id");
                psFree(output);
                psFree(warps);
                return NULL;
            }

//            psArrayAdd(warps, 0, warp_id);
        }

        // generate a random-valued vector, return an index sorted by the
        // random values
        psVector *randomVector = psVectorAlloc(psArrayLength(output), PS_TYPE_F32);
        psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0);
        for (int i = 0; i < randomVector->n; i++) {
            randomVector->data.F32[i] = psRandomUniform(rng);
        }
        psVector *indexVector = psVectorSortIndex(NULL, randomVector);
        psFree(randomVector);

        // accept for first n of the sequence
        valid_warpids = psVectorAlloc(randomLimit, PS_TYPE_S64);
        for (int i = 0; i < randomLimit; i++ ){
//            int j = indexVector->data.S32[i];
//            valid_warpids->data[i] = psMemIncrRefCounter (warps->data[j]);
        }
        psFree(indexVector);
        psFree(warps);
    }


    psHash *stacks = psHashAlloc(psArrayLength(output));

    // loop over the array of metadata and build a hash keyed by tess_id &
    // skycell_id
    for (long i = 0; i < psArrayLength(output); i++) {
        psMetadata *md = output->data[i];

        bool status;
        if (valid_warpids) {
//            psS64 warp_id = psMetadataLookupS64(&status, md, "warp_id");
            if (!status) {
                psError(PS_ERR_UNKNOWN, false, "failed to lookup warp_id");
                psFree(valid_warpids);
                psFree(output);
                return NULL;
            }

            // is this a warp_id that should be left out of the stack set(s)?
//            for (long i = 0; i < psArrayLength(valid_warpids); i++) {
//                if (valid_warpids->data[i] == warp_id) {
//                    continue;
//                }
//            }
        }

        // pull out the skycell_id, & tess_id
        psString skycell_id = psMetadataLookupStr(&status, md, "skycell_id");
        if (!status) {
            psError(PS_ERR_UNKNOWN, false, "failed to lookup skycell_id");
            psFree(valid_warpids);
            psFree(output);
            return NULL;
        }

        psString tess_id = psMetadataLookupStr(&status, md, "tess_id");
        if (!status) {
            psError(PS_ERR_UNKNOWN, false, "failed to lookup tess_id");
            psFree(valid_warpids);
            psFree(output);
            return NULL;
        }

        // group the warps by skycell_id & tess_id
        psString key = NULL;
        psStringAppend(&key, "%s:%s", skycell_id, tess_id);

        // check to see if the hash key already exists
        psArray *col = psHashLookup(stacks, key);
        if (!col) {
            // if it doesn't, create an new psArray for this stack
            col = psArrayAllocEmpty(0);
            psHashAdd(stacks, key, col);
        }
        // add this warp to the stack for this key
        psArrayAdd(col, 0, md);
        psFree(key);

    }
    psFree(valid_warpids);
    psFree(output);

    psArray *grouped = psHashToArray(stacks);
    psFree(stacks);

    if (!psDBTransaction(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    // loop over groups
    for (long i = 0; i < psArrayLength(grouped); i++) {
        psArray *col = grouped->data[i];

        // pull the skycell_id & tess_id from the first warp in the stack
        bool status;
        psString skycell_id = psMetadataLookupStr(&status, col->data[0], "skycell_id");
        if (!status) {
            psError(PS_ERR_UNKNOWN, false, "failed to lookup skycell_id");
            psFree(grouped);
            return NULL;
        }

        psString tess_id = psMetadataLookupStr(&status, col->data[0], "tess_id");
        if (!status) {
            psError(PS_ERR_UNKNOWN, false, "failed to lookup tess_id");
            psFree(grouped);
            return NULL;
        }

        // create a new stackRun for the group
        stackRunRow *run = stackRunRowAlloc(
            0,          // ID
            "run",      // state
            workdir,
            NULL,       // dvodb
            registered,
            skycell_id,
            tess_id
        );
        if (!stackRunInsertObject(config->dbh, run)) {
            if (!psDBRollback(config->dbh)) {
                psError(PS_ERR_UNKNOWN, false, "database error");
            }
            psError(PS_ERR_UNKNOWN, false, "database error");
            psFree(run);
            psFree(grouped);
            return false;
        }

        // figure out the new stack_id
        psS64 stack_id = psDBLastInsertID(config->dbh);
        run->stack_id = stack_id;

        if (!stackRunPrintObject(stdout, run, !simple)) {
            psError(PS_ERR_UNKNOWN, false, "failed to print object");
            psFree(run);
            psFree(grouped);
            return false;
        }
        psFree(run);

        // loop over this stack and add each warp to the stackRun
        for (long j = 0; j < psArrayLength(col); j++) {
            bool status;
            psS64 warp_id = psMetadataLookupS64(&status, col->data[j], "warp_id");
            if (!status) {
                if (!psDBRollback(config->dbh)) {
                    psError(PS_ERR_UNKNOWN, false, "database error");
                }
                psError(PS_ERR_UNKNOWN, false, "failed to lookup warp_id");
                psFree(grouped);
                return NULL;
            }

            if (!stackInputSkyfileInsert(config->dbh,
                stack_id,
                warp_id
            )) {
                if (!psDBRollback(config->dbh)) {
                    psError(PS_ERR_UNKNOWN, false, "database error");
                }
                psError(PS_ERR_UNKNOWN, false, "database error");
                psFree(grouped);
                return false;
            }

        }

    }

    // point of no return
    if (!psDBCommit(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    psFree(grouped);

    return true;
}


static bool definerunMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    // required options
    PXOPT_LOOKUP_STR(workdir, config->args, "-workdir", true, false);
    PXOPT_LOOKUP_STR(skycell_id, config->args, "-skycell_id", true, false);
    PXOPT_LOOKUP_STR(tess_id, config->args, "-tess_id", true, false);

    // default
    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);
    PXOPT_LOOKUP_TIME(registered, config->args, "-registered", false, false);

    // we have to support multipe exp_ids
    psMetadataItem *warp_ids = psMetadataLookup(config->args, "-warp_id");
    if (!warp_ids) {
        // this shouldn't actually happen when using psArgs
        psError(PS_ERR_UNKNOWN, true, "-warp_id is required");
        return false;
    }

    stackRunRow *run = stackRunRowAlloc(
            0,          // ID
            "run",      // state
            workdir,
            NULL,       // dvodb
            registered,
            skycell_id,
            tess_id
    );
    if (!run) {
        psError(PS_ERR_UNKNOWN, false, "failed to alloc stackRun object");
        return true;
    }

    if (!psDBTransaction(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    if (!stackRunInsertObject(config->dbh, run)) {
        if (!psDBRollback(config->dbh)) {
            psError(PS_ERR_UNKNOWN, false, "database error");
        }
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(run);
        return true;
    }

    // get the assigned warp_id
    run->stack_id = psDBLastInsertID(config->dbh);

    // insert the stackInputSkyfile rows
    psListIterator *iter = psListIteratorAlloc(warp_ids->data.list, 0, false);
    psMetadataItem *item = NULL;
    while ((item = psListGetAndIncrement(iter))) {
        // if the value is NULL this is probably the first pass through the
        // loop and -warp_id was not specified at all
        if (!item->data.V) {
            if (!psDBRollback(config->dbh)) {
                psError(PS_ERR_UNKNOWN, false, "database error");
            }
            psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -warp_id");
            return false;
        }
        if (!stackInputSkyfileInsert(config->dbh, run->stack_id, (psS64)atoll((char *)item->data.V))) {
            if (!psDBRollback(config->dbh)) {
                psError(PS_ERR_UNKNOWN, false, "database error");
            }
            psError(PS_ERR_UNKNOWN, false, "failed to insert stackInputSkyfile rows");
            return false;
        }
    }
    psFree(iter);

    // point of no return
    if (!psDBCommit(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    if (!stackRunPrintObject(stdout, run, !simple)) {
            psError(PS_ERR_UNKNOWN, false, "failed to print object");
            psFree(run);
            return false;
    }

    psFree(run);

    return true;
}


static bool updaterunMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    PXOPT_LOOKUP_S64(stack_id, config->args, "-stack_id", true, false);
    PXOPT_LOOKUP_STR(state, config->args, "-state", true, false);

    if (state) {
        // set detRun.state to state
        return setstackRunState(config, stack_id, state);
    }

    return true;
}


static bool addinputskyfileMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    PXOPT_LOOKUP_S64(stack_id, config->args, "-stack_id", true, false);
    PXOPT_LOOKUP_S64(warp_id, config->args, "-warp_id", true, false);

    // XXX need to validate the warp_id here
    // XXX instead of validiting it here we should just use forgein key
    // constrants
    if (!stackInputSkyfileInsert(config->dbh,
            stack_id,
            warp_id
        )) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    return true;
}


static bool inputskyfileMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    psMetadata *where = psMetadataAlloc();
    PXOPT_COPY_S64(config->args, where, "-warp_id", "warp_id", "==");
    PXOPT_COPY_S64(config->args, where, "-stack_id", "stack_id", "==");

    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);

    psString query = pxDataGet("stacktool_inputskyfile.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

    if (psListLength(where->list)) {
        psString whereClause = psDBGenerateWhereConditionSQL(where, "stackInputSkyfile");
        psStringAppend(&query, " AND %s", whereClause);
        psFree(whereClause);
    }
    psFree(where);

    // treat limit == 0 as "no limit"
    if (limit) {
        psString limitString = psDBGenerateLimitSQL(limit);
        psStringAppend(&query, " %s", limitString);
        psFree(limitString);
    }

    if (!p_psDBRunQuery(config->dbh, query)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }
    psFree(query);

    psArray *output = p_psDBFetchResult(config->dbh);
    if (!output) {
        psErrorCode err = psErrorCodeLast();
        switch (err) {
            case PS_ERR_DB_CLIENT:
                psError(PXTOOLS_ERR_SYS, false, "database error");
            case PS_ERR_DB_SERVER:
                psError(PXTOOLS_ERR_PROG, false, "database error");
            default:
                psError(PXTOOLS_ERR_PROG, false, "unknown error");
        }

        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("stacktool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    if (psArrayLength(output)) {
        // negative simple so the default is true
        if (!ippdbPrintMetadatas(stdout, output, "stackInputSkyfile", !simple)) {
            psError(PS_ERR_UNKNOWN, false, "failed to print array");
            psFree(output);
            return false;
        }
    }

    psFree(output);

    return true;
}


static bool tosumMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    psMetadata *where = psMetadataAlloc();
    PXOPT_COPY_S64(config->args, where, "-warp_id", "warp_id", "==");
    PXOPT_COPY_S64(config->args, where, "-stack_id", "stack_id", "==");

    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);

    psString query = pxDataGet("stacktool_tosum.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

    if (psListLength(where->list)) {
        psString whereClause = psDBGenerateWhereConditionSQL(where, "stackSumSkyfile");
        psStringAppend(&query, " AND %s", whereClause);
        psFree(whereClause);
    }
    psFree(where);

    // treat limit == 0 as "no limit"
    if (limit) {
        psString limitString = psDBGenerateLimitSQL(limit);
        psStringAppend(&query, " %s", limitString);
        psFree(limitString);
    }

    if (!p_psDBRunQuery(config->dbh, query)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }
    psFree(query);

    psArray *output = p_psDBFetchResult(config->dbh);
    if (!output) {
        psErrorCode err = psErrorCodeLast();
        switch (err) {
            case PS_ERR_DB_CLIENT:
                psError(PXTOOLS_ERR_SYS, false, "database error");
            case PS_ERR_DB_SERVER:
                psError(PXTOOLS_ERR_PROG, false, "database error");
            default:
                psError(PXTOOLS_ERR_PROG, false, "unknown error");
        }

        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("stacktool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    if (psArrayLength(output)) {
        // negative simple so the default is true
        if (!ippdbPrintMetadatas(stdout, output, "stackSumSkyfile", !simple)) {
            psError(PS_ERR_UNKNOWN, false, "failed to print array");
            psFree(output);
            return false;
        }
    }

    psFree(output);

    return true;
}


static bool addsumskyfileMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    // required
    PXOPT_LOOKUP_S64(stack_id, config->args, "-stack_id", true, false);

    // optional
    PXOPT_LOOKUP_STR(uri, config->args, "-uri", false, false);
    PXOPT_LOOKUP_STR(path_base, config->args, "-path_base", false, false);
    PXOPT_LOOKUP_F64(bg, config->args, "-bg", false, false);
    PXOPT_LOOKUP_F64(bg_stdev, config->args, "-bg_stdev", false, false);
    PXOPT_LOOKUP_F32(dtime_stack, config->args, "-dtime_stack", false, false);
    PXOPT_LOOKUP_STR(hostname, config->args, "-hostname", false, false);
    PXOPT_LOOKUP_F32(good_frac, config->args, "-good_frac", false, false);

    // default values
    PXOPT_LOOKUP_S16(code, config->args, "-code", false, false);

    if (!psDBTransaction(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    // XXX need to validate the stack_id here
    // XXX instead of validiting it here we should just use forgein key
    // constrants
    if (!stackSumSkyfileInsert(config->dbh,
                               stack_id,
                               uri,
                               path_base,
                               bg,
                               bg_stdev,
                               dtime_stack,
                               hostname,
                               good_frac,
                               code
          )) {
        if (!psDBRollback(config->dbh)) {
            psError(PS_ERR_UNKNOWN, false, "database error");
        }
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    if (!setstackRunState(config, stack_id, "stop")) {
        if (!psDBRollback(config->dbh)) {
            psError(PS_ERR_UNKNOWN, false, "database error");
        }
        psError(PS_ERR_UNKNOWN, false, "failed to change stackRun's state");
        return false;
    }

    // point of no return
    if (!psDBCommit(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    return true;
}


static bool sumskyfileMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    psMetadata *where = psMetadataAlloc();
    PXOPT_COPY_S64(config->args, where, "-warp_id", "warp_id", "==");
    PXOPT_COPY_S64(config->args, where, "-stack_id", "stack_id", "==");

    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);

    psString query = pxDataGet("stacktool_sumskyfile.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

    if (psListLength(where->list)) {
        psString whereClause = psDBGenerateWhereConditionSQL(where, "stackSumSkyfile");
        psStringAppend(&query, " AND %s", whereClause);
        psFree(whereClause);
    }
    psFree(where);

    // treat limit == 0 as "no limit"
    if (limit) {
        psString limitString = psDBGenerateLimitSQL(limit);
        psStringAppend(&query, " %s", limitString);
        psFree(limitString);
    }

    if (!p_psDBRunQuery(config->dbh, query)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }
    psFree(query);

    psArray *output = p_psDBFetchResult(config->dbh);
    if (!output) {
        psErrorCode err = psErrorCodeLast();
        switch (err) {
            case PS_ERR_DB_CLIENT:
                psError(PXTOOLS_ERR_SYS, false, "database error");
            case PS_ERR_DB_SERVER:
                psError(PXTOOLS_ERR_PROG, false, "database error");
            default:
                psError(PXTOOLS_ERR_PROG, false, "unknown error");
        }

        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("stacktool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    if (psArrayLength(output)) {
        if (!ippdbPrintMetadatas(stdout, output, "stackSumSkyfile", !simple)) {
            psError(PS_ERR_UNKNOWN, false, "failed to print array");
            psFree(output);
            return false;
        }
    }

    psFree(output);

    return true;
}


static bool revertsumskyfileMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    psMetadata *where = psMetadataAlloc();
    PXOPT_COPY_S64(config->args, where, "-stack_id", "stack_id", "==");
    PXOPT_COPY_S16(config->args, where, "-code", "fault", "==");

    psString query = pxDataGet("stacktool_revertsumskyfile.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

    if (psListLength(where->list)) {
        psString whereClause = psDBGenerateWhereConditionSQL(where, "stackSumSkyfile");
        psStringAppend(&query, " AND %s", whereClause);
        psFree(whereClause);
    }
    psFree(where);

    if (!p_psDBRunQuery(config->dbh, query)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }
    psFree(query);

    if (psDBAffectedRows(config->dbh) < 1) {
        psError(PS_ERR_UNKNOWN, false, "should have affected atleast 1 row");
        return false;
    }

    return true;
}


static bool setstackRunState(pxConfig *config, psS64 stack_id, const char *state)
{
    PS_ASSERT_PTR_NON_NULL(state, false);

    // check that state is a valid string value
    if (!(
            (strncmp(state, "run", 4) == 0)
            || (strncmp(state, "stop", 5) == 0)
            || (strncmp(state, "reg", 4) == 0)
        )
    ) {
        psError(PS_ERR_UNKNOWN, false,
                "invalid warpRun state: %s", state);
        return false;
    }

    char *query = "UPDATE stackRun SET state = '%s' WHERE stack_id = %"PRId64;
    if (!p_psDBRunQuery(config->dbh, query, state, stack_id)) {
        psError(PS_ERR_UNKNOWN, false,
                "failed to change state for stack_id %"PRId64, stack_id);
        return false;
    }

    return true;
}
