/*
 *  libpipi       Proper image processing implementation library
 *  Copyright (c) 2004-2008 Sam Hocevar <sam@zoy.org>
 *                All Rights Reserved
 *
 *  $Id$
 *
 *  This library is free software. It comes without any warranty, to
 *  the extent permitted by applicable law. You can redistribute it
 *  and/or modify it under the terms of the Do What The Fuck You Want
 *  To Public License, Version 2, as published by Sam Hocevar. See
 *  http://sam.zoy.org/wtfpl/COPYING for more details.
 */

/*
 * ordered.c: Bayer ordered dithering functions
 */

#include "config.h"
#include "common.h"

#include "pipi.h"
#include "pipi_internals.h"

static const int kernel8x8[8 * 8] =
{
   0,  32,   8,  40,   2,  34,  10,  42,
  48,  16,  56,  24,  50,  18,  58,  26,
  12,  44,   4,  36,  14,  46,   6,  38,
  60,  28,  52,  20,  62,  30,  54,  22,
   3,  35,  11,  43,   1,  33,   9,  41,
  51,  19,  59,  27,  49,  17,  57,  25,
  15,  47,   7,  39,  13,  45,   5,  37,
  63,  31,  55,  23,  61,  29,  53,  21,
};

pipi_image_t *pipi_dither_ordered(pipi_image_t *img)
{
    pipi_image_t *dst;
    pipi_pixels_t *dstp;
    float *dstdata;
    int x, y, w, h;

    w = img->w;
    h = img->h;

    dst = pipi_copy(img);
    dstp = pipi_getpixels(dst, PIPI_PIXELS_Y_F);
    dstdata = (float *)dstp->pixels;

    for(y = 0; y < h; y++)
    {
        for(x = 0; x < w; x++)
        {
            float p, q;

            p = dstdata[y * w + x];
            q = p > (1. + kernel8x8[(y % 8) * 8 + (x % 8)]) / 65. ? 1. : 0.;
            dstdata[y * w + x] = q;
        }
    }

    return dst;
}