/*
 * chiptool.c
 *
 * Copyright (C) 2006  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 HAVE_CONFIG_H
#include <config.h>
#endif

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

#include "pxtools.h"
#include "pxdata.h"

#include "chiptool.h"
#include "camtool.h"

static bool queueMode(pxConfig *config);
static bool pendingimfileMode(pxConfig *config);
static bool addprocessedimfileMode(pxConfig *config);
static bool processedimfileMode(pxConfig *config);
static bool revertprocessedimfileMode(pxConfig *config);
static bool updateprocessedimfileMode(pxConfig *config);
static bool blockMode(pxConfig *config);
static bool maskedMode(pxConfig *config);
static bool unblockMode(pxConfig *config);

static bool chipProcessedCompleteExp(pxConfig *config);

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

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

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

    switch (config->mode) {
        MODECASE(CHIPTOOL_MODE_QUEUE,                   queueMode);
        MODECASE(CHIPTOOL_MODE_PENDINGIMFILE,           pendingimfileMode);
        MODECASE(CHIPTOOL_MODE_ADDPROCESSEDIMFILE,      addprocessedimfileMode);
        MODECASE(CHIPTOOL_MODE_PROCESSEDIMFILE,         processedimfileMode);
        MODECASE(CHIPTOOL_MODE_REVERTPROCESSEDIMFILE,   revertprocessedimfileMode);
        MODECASE(CHIPTOOL_MODE_UPDATEPROCESSEDIMFILE,updateprocessedimfileMode);
        MODECASE(CHIPTOOL_MODE_BLOCK,                   blockMode);
        MODECASE(CHIPTOOL_MODE_MASKED,                  maskedMode);
        MODECASE(CHIPTOOL_MODE_UNBLOCK,                 unblockMode);
        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);
}

#define ADDRENAMEPARAMSTR(from, to, oldname, newname, comment) \
{ \
    bool status = false; \
    psString str = psMetadataLookupStr(&status, from, "-" oldname); \
    if (!status) { \
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -" oldname); \
        return false; \
    } \
    if (str) { \
        if (!psMetadataAddStr(to, PS_LIST_TAIL, newname, PS_META_DUPLICATE_OK, comment, str)) { \
            psError(PS_ERR_UNKNOWN, false, "failed to add item " newname); \
            psFree(to); \
            return false; \
        } \
    } \
}

#define ADDPARAMSTR(from, to, name) \
  ADDRENAMEPARAMSTR(from, to, name, name, "==")

#define ADDRENAMEPARAMF(from, to, type, oldname, newname, comment) \
{ \
    bool status = false; \
    ps##type var = psMetadataLookup##type(&status, from, "-" oldname); \
    if (!status) { \
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -" oldname); \
        return false; \
    } \
    if (!isnan(var)) { \
        if (!psMetadataAdd##type(to, PS_LIST_TAIL, newname, PS_META_DUPLICATE_OK, comment, var)) { \
            psError(PS_ERR_UNKNOWN, false, "failed to add item " newname); \
            psFree(to); \
            return false; \
        } \
    } \
}

#define ADDPARAMF(from, to, type, name) \
  ADDRENAMEPARAMF(from, to, type, name, name, "==")

static bool queueMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, NULL);

    psMetadata *where = psMetadataAlloc();
    // convert exp_id into a psS64
{
    bool status = false;
    psString var = psMetadataLookupStr(&status, config->args, "-exp_id");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -exp_id");
        return false;
    }
    if (var) {
        if (!psMetadataAddS64(where, PS_LIST_TAIL, "exp_id", 0, "==", (psS64)atoll(var))) {
            psError(PS_ERR_UNKNOWN, false, "failed to add item exp_id");
            psFree(where);
            return false; 
        }
    }
}
    ADDPARAMSTR(config->args, where, "exp_name");
    ADDRENAMEPARAMSTR(config->args, where, "inst", "camera", "==");
    ADDPARAMSTR(config->args, where, "telescope");
    ADDPARAMSTR(config->args, where, "dateobs_begin");
    ADDPARAMSTR(config->args, where, "dateobs_end");
    ADDPARAMSTR(config->args, where, "exp_tag");
    ADDPARAMSTR(config->args, where, "exp_type");
    ADDPARAMSTR(config->args, where, "filelevel");
    ADDPARAMSTR(config->args, where, "reduction");
    ADDPARAMSTR(config->args, where, "filter");
    ADDRENAMEPARAMF(config->args, where, F64, "airmass_min", "airmass", ">=");
    ADDRENAMEPARAMF(config->args, where, F64, "airmass_max", "airmass", "<");
    ADDRENAMEPARAMF(config->args, where, F64, "ra_min", "ra", ">=");
    ADDRENAMEPARAMF(config->args, where, F64, "ra_max", "ra", "<");
    ADDRENAMEPARAMF(config->args, where, F64, "decl_min", "decl", ">=");
    ADDRENAMEPARAMF(config->args, where, F64, "decl_max", "decl", "<");
    ADDRENAMEPARAMF(config->args, where, F32, "exp_time_min", "exp_time", ">=");
    ADDRENAMEPARAMF(config->args, where, F32, "exp_time_max", "exp_time", "<");
    ADDRENAMEPARAMF(config->args, where, F32, "sat_pixel_frac_min", "sat_pixel_frac", ">=");
    ADDRENAMEPARAMF(config->args, where, F32, "sat_pixel_frac_max", "sat_pixel_frac", "<");
    ADDRENAMEPARAMF(config->args, where, F64, "bg_min", "bt", ">=");
    ADDRENAMEPARAMF(config->args, where, F64, "bg_max", "bt", "<");
    ADDRENAMEPARAMF(config->args, where, F64, "bg_stdev_min", "bg_stdev", ">=");
    ADDRENAMEPARAMF(config->args, where, F64, "bg_stdev_max", "bg_stdev", "<");
    ADDRENAMEPARAMF(config->args, where, F64, "bg_mean_stdev_min", "bg_mean_stdev", ">=");
    ADDRENAMEPARAMF(config->args, where, F64, "bg_mean_stdev_max", "bg_mean_stdev", "<");
    ADDRENAMEPARAMF(config->args, where, F64, "alt_min", "alt", ">=");
    ADDRENAMEPARAMF(config->args, where, F64, "alt_max", "alt", "<");
    ADDRENAMEPARAMF(config->args, where, F64, "az_min", "az", ">=");
    ADDRENAMEPARAMF(config->args, where, F64, "az_max", "az", "<");
    ADDRENAMEPARAMF(config->args, where, F32, "ccd_temp_min", "ccd_temp", ">=");
    ADDRENAMEPARAMF(config->args, where, F32, "ccd_temp_max", "ccd_temp", "<");
    ADDRENAMEPARAMF(config->args, where, F64, "posang_min", "posang", ">=");
    ADDRENAMEPARAMF(config->args, where, F64, "posang_max", "posang", "<");
    ADDPARAMSTR(config->args, where, "object");
    ADDRENAMEPARAMF(config->args, where, F32, "solang_min", "solang", ">=");
    ADDRENAMEPARAMF(config->args, where, F32, "solang_max", "solang", "<");

    if (where->list->n < 1) {
        psFree(where);
        where = NULL;
    }

    bool status = false;
    psString workdir = psMetadataLookupStr(&status, config->args, "-set_workdir");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -set_workdir");
        return false;
    }

    psString label = psMetadataLookupStr(&status, config->args, "-set_label");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -set_label");
        return false;
    }

    psString reduction = psMetadataLookupStr(&status, config->args, "-set_reduction");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -set_reduction");
        return false;
    }

    psString expgroup = psMetadataLookupStr(&status, config->args, "-set_expgroup");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -set_expgroup");
        return false;
    }

    psString dvodb = psMetadataLookupStr(&status, config->args, "-set_dvodb");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -set_dvodb");
        return false;
    }

    // find the exp_id of all the exposures that we want to queue up.
    psString query = pxDataGet("chiptool_find_rawexp.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

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

    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) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("chiptool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    // start a transaction so we don't end up with an exp without any associted
    // imfiles
    if (!psDBTransaction(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(output);
        return false;
    }

    // loop over our list of exp_ids
    for (long i = 0; i < psArrayLength(output); i++) {
        psMetadata *md = output->data[i];

        psS64 exp_id = psMetadataLookupS64(&status, md, "exp_id");
        if (!status) {
            psError(PS_ERR_UNKNOWN, false, "failed to lookup value for exp_id");
            psFree(output);
            return false;
        }

        // queue the exp
        if (!pxchipQueueByExpTag(config, exp_id, workdir, label, reduction, expgroup, dvodb)) {
            if (!psDBRollback(config->dbh)) {
                psError(PS_ERR_UNKNOWN, false, "database error");
            }
            psError(PS_ERR_UNKNOWN, false,
                    "failed to trying to queue exp_id: %" PRId64, exp_id);
            psFree(output);
            return false;
        }
    }
    psFree(output);

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

    return true;
}

static bool pendingimfileMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, NULL);

    bool status = false;
    psU64 limit = psMetadataLookupU64(&status, config->args, "-limit");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -limit");
        return false;
    }

    // XXX does this need to be constrained so that it won't return any results
    // if a match chipPendingExp hasn't been registered?
    psString query = pxDataGet("chiptool_pendingimfile.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

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

    // 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) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("chiptool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    bool simple = false;
    {
        bool status = false;
        simple = psMetadataLookupBool(&status, config->args, "-simple");
        if (!status) {
            psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -simple");
            return false;
        }
    }

    if (!convertIdToStr(output)) {
        psError(PS_ERR_UNKNOWN, false, "failed to convert id fields into a strings");
        psFree(output);
        return false;
    }

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

    psFree(output);

    return true;
}


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

    bool status = false;
    // chip_id, ext_tag, class_id are required
    psString chip_id = psMetadataLookupStr(&status, config->args, "-chip_id");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -chip_id");
        return false;
    }
    if (!chip_id) {
        psError(PS_ERR_UNKNOWN, true, "-chip_id is required");
        return false;
    }

    psString exp_id = psMetadataLookupStr(&status, config->args, "-exp_id");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -exp_id");
        return false;
    }
    if (!exp_id) {
        psError(PS_ERR_UNKNOWN, true, "-exp_id is required");
        return false;
    }

    psString class_id = psMetadataLookupStr(&status, config->args, "-class_id");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -class_id");
        return false;
    }
    if (!class_id) {
        psError(PS_ERR_UNKNOWN, true, "-class_id is required");
        return false;
    }

    psString uri = psMetadataLookupStr(&status, config->args, "-uri");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -uri");
        return false;
    }

    psF32 bg = psMetadataLookupF32(&status, config->args, "-bg");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -bg");
        return false;
    }

    psF32 bg_stdev = psMetadataLookupF32(&status, config->args, "-bg_stdev");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -bg_stdev");
        return false;
    }

    psF32 bg_mean_stdev = psMetadataLookupF32(&status, config->args, "-bg_mean_stdev");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -bg_mean_stdev");
        return false;
    }

    psF32 bias = psMetadataLookupF32(&status, config->args, "-bias");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -bias");
        return false;
    }

    psF32 bias_stdev = psMetadataLookupF32(&status, config->args, "-bias_stdev");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -bias_stdev");
        return false;
    }

    psF32 fringe_0 = psMetadataLookupF32(&status, config->args, "-fringe_0");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -fringe_0");
        return false;
    }

    psF32 fringe_1 = psMetadataLookupF32(&status, config->args, "-fringe_1");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -fringe_1");
        return false;
    }

    psF32 fringe_2 = psMetadataLookupF32(&status, config->args, "-fringe_2");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -fringe_2");
        return false;
    }

    psF32 sigma_ra = psMetadataLookupF32(&status, config->args, "-sigma_ra");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -sigma_ra");
        return false;
    }

    psF32 sigma_dec = psMetadataLookupF32(&status, config->args, "-sigma_dec");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -sigma_dec");
        return false;
    }

    psF32 ap_resid = psMetadataLookupF32(&status, config->args, "-ap_resid");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -ap_resid");
        return false;
    }

    psF32 ap_resid_stdev = psMetadataLookupF32(&status, config->args, "-ap_resid_stdev");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -ap_resid_stdev");
        return false;
    }

    psF32 fwhm = psMetadataLookupF32(&status, config->args, "-fwhm");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -fwhm");
        return false;
    }

    psF32 fwhm_range = psMetadataLookupF32(&status, config->args, "-fwhm_range");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -fwhm_range");
        return false;
    }

    psS32 n_stars = psMetadataLookupS32(&status, config->args, "-n_stars");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -n_stars");
        return false;
    }

    psS32 n_extended = psMetadataLookupS32(&status, config->args, "-n_extended");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -n_extended");
        return false;
    }

    psS32 n_cr = psMetadataLookupS32(&status, config->args, "-n_cr");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -n_cr");
        return false;
    }

    psS32 n_astrom = psMetadataLookupS32(&status, config->args, "-n_astrom");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -n_astrom");
        return false;
    }

    // optional
    psString path_base = psMetadataLookupStr(&status, config->args, "-path_base");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -path_base");
        return false;
    }

    // default values
    psS16 code = psMetadataLookupS16(&status, config->args, "-code");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -code");
        return false;
    }

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

    chipProcessedImfileRow *imfile = chipProcessedImfileRowAlloc(
        (psS64)atoll(chip_id),
        (psS64)atoll(exp_id),
        class_id,
        uri,
        bg,
        bg_stdev,
        bg_mean_stdev,
        bias,
        bias_stdev,
        fringe_0,
        fringe_1,
        fringe_2,
        sigma_ra,
        sigma_dec,
        ap_resid,
        ap_resid_stdev,
        fwhm,
        fwhm_range,
        n_stars,
        n_extended,
        n_cr,
        n_astrom,
        path_base,
        code
    );
    if (!imfile) {
        // rollback
        if (!psDBRollback(config->dbh)) {
            psError(PS_ERR_UNKNOWN, false, "database error");
        }
        psError(PS_ERR_UNKNOWN, false, "failed to alloc chipProcessedImfileRow object");
        return false;
    }
    if (!chipProcessedImfileInsertObject(config->dbh, imfile)) {
        // rollback
        if (!psDBRollback(config->dbh)) {
            psError(PS_ERR_UNKNOWN, false, "database error");
        }
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(imfile);
        return false;
    }



    // XXX I've decided to make the transaction cover the Exp migration as
    // well.  Otherwise, if the last imfile in an exp is moved and the exp
    // migration fails then the data base is left in a satuation where the exp
    // migration can't happen.

    if (!chipProcessedCompleteExp(config)) {
        // rollback
        if (!psDBRollback(config->dbh)) {
            psError(PS_ERR_UNKNOWN, false, "database error");
        }
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

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

    return true;
}


static bool processedimfileMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, NULL);

    bool status = false;
    psU64 limit = psMetadataLookupU64(&status, config->args, "-limit");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -limit");
        return false;
    }

    bool faulted = psMetadataLookupU64(&status, config->args, "-faulted");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -faulted");
        return false;
    }

    // XXX does this need to be constrained so that it won't return any results
    // if a match chipPendingExp hasn't been registered?
    psString query = pxDataGet("chiptool_processedimfile.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

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

    if (faulted) {
        // list only faulted rows
        psStringAppend(&query, " %s", "AND chipProcessedImfile.fault != 0");
    } else {
        // don't list faulted rows
        psStringAppend(&query, " %s", "AND chipProcessedImfile.fault = 0");
    }

    // 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) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("chiptool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    bool simple = false;
    {
        bool status = false;
        simple = psMetadataLookupBool(&status, config->args, "-simple");
        if (!status) {
            psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -simple");
            return false;
        }
    }

    if (!convertIdToStr(output)) {
        psError(PS_ERR_UNKNOWN, false, "failed to convert id fields into a strings");
        psFree(output);
        return false;
    }

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

    psFree(output);

    return true;
}

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

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

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

    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 updateprocessedimfileMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    bool status = false;
    psS16 code = psMetadataLookupS16(&status, config->args, "-code");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -code");
        return false;
    }
    if (code == INT16_MAX) {
        psError(PS_ERR_UNKNOWN, true, "-code is required");
        return false;
    }

    if (!pxSetFaultCode(config->dbh, "chipProcessedImfile", config->where, code)) {
        psError(PS_ERR_UNKNOWN, false, "failed to set set fault flag");
        return false;
    }

    return true;
}


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

    bool status = false;
    psString label = psMetadataLookupStr(&status, config->args, "-label");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -label");
        return false;
    }
    if (!label) {
        psError(PS_ERR_UNKNOWN, true, "-label is required");
        return false;
    }

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

    return true;
}


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

    psString query = psStringCopy("SELECT * FROM chipMask");

    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) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("chiptool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    bool simple = false;
    {
        bool status = false;
        simple = psMetadataLookupBool(&status, config->args, "-simple");
        if (!status) {
            psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -simple");
            return false;
        }
    }

    if (!convertIdToStr(output)) {
        psError(PS_ERR_UNKNOWN, false, "failed to convert id fields into a strings");
        psFree(output);
        return false;
    }

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

    psFree(output);

    return true;
}


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

    bool status = false;
    psString label = psMetadataLookupStr(&status, config->args, "-label");
    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "failed to lookup value for -label");
        return false;
    }
    if (!label) {
        psError(PS_ERR_UNKNOWN, true, "-label is required");
        return false;
    }

    char *query = "DELETE FROM chipMask WHERE label = '%s'";

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

    return true;
}


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

    // look for completed chipPendingExp
    // migrate them to chipProccessedExp & camPendingExp
    psString query = pxDataGet("chiptool_completely_processed_exp.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

    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) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("chiptool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    for (long i = 0; i < psArrayLength(output); i++) {
        psMetadata *row = output->data[i];

        chipRunRow *chipRun = chipRunObjectFromMetadata(row);
        // set chipRun.state to 'stop'
        if (!pxchipRunSetState(config, chipRun->chip_id, "stop")) {
            psError(PS_ERR_UNKNOWN, false, "failed to change chipRun.state for chip_id: %" PRId64, chipRun->chip_id);
            psFree(chipRun);
            psFree(output);
            return false;
        }

        // camQueueChipID() can only be run after chipRun.state has been set to
        // stop
        if (!pxcamQueueByChipID(config,
                    chipRun->chip_id,
                    chipRun->workdir,
                    chipRun->label,
                    chipRun->reduction,
                    chipRun->expgroup,
                    chipRun->dvodb
        )) {
            // rollback
            if (!psDBRollback(config->dbh)) {
                psError(PS_ERR_UNKNOWN, false, "database error");
            }
            psError(PS_ERR_UNKNOWN, false, "failed to queue camPendingExp");
            psFree(chipRun);
            psFree(output);
            return false;
        }
        psFree(chipRun);
    }

    psFree(output);

    return true;
}
