// Copyright (C) 2006  Paul A. Price (price@ifa.hawaii.edu)
//
// 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; either version 2 of the License, or
// (at your option) any later version.
//
// 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 this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

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

#include <stdio.h>
#include "pslib.h"
#include "pois.h"

poisStamp *poisStampAlloc(void)
{
    poisStamp *stamp = (poisStamp*)psAlloc(sizeof(poisStamp));
    stamp->x = 0;
    stamp->y = 0;
    stamp->status = POIS_STAMP_RESET;
    stamp->matrix = NULL;
    stamp->vector = NULL;
    psMemSetDeallocator(stamp, (psFreeFunc)poisStampFree);

    return stamp;
}

void poisStampFree(poisStamp *stamp)
{
    if (stamp->matrix) {
        psFree(stamp->matrix);
    }
    if (stamp->vector) {
        psFree(stamp->vector);
    }
    psFree(stamp);
}


// Return true if the stamp is OK
bool poisCheckStamp(const psImage *image, // Image to check for threshold
                    const psImage *mask, // Mask to check for bad pixels
                    int x, int y,       // Pixel coordinates
                    const poisConfig *config // Configuration
    )
{
    if (x < config->footprint + config->xKernel ||
        y < config->footprint + config->yKernel ||
        x > config->xImage - config->footprint - config->xKernel ||
        y > config->yImage - config->footprint - config->yKernel ||
        image->data.F32[y][x] < config->threshold) {
        psTrace("pois.checkStamp", 9, "Rejecting stamp at %d,%d (border/threshold)\n", x, y);
        return false;
    }

    // Check the footprint
    bool ok = true;                     // Is the footprint OK?
    int footprint = config->footprint;  // Footprint size
    for (int v = y - footprint; v <= y + footprint && ok; v++) {
        for (int u = x - footprint; u <= x + footprint && ok; u++) {
            if (mask->data.U8[v][u] &
                (POIS_MASK_BAD | POIS_MASK_NEAR_BAD | POIS_MASK_STAMP)) {
                psTrace("pois.checkStamp", 9, "Rejecting stamp at %d,%d (bad footprint)\n", x, y);
                ok = false;
            }
        }
    }

    return ok;
}

