/*
 *  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.
 */

/*
 * halftone.c: screening halftone dithering functions
 */

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

#include <math.h>

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

pipi_image_t *pipi_dither_halftone(pipi_image_t *img, double r, double angle)
{
    double sint, cost;
    pipi_image_t *dst;
    pipi_pixels_t *dstp;
    float *dstdata;
    int x, y, w, h;

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

    cost = cos(angle * (M_PI / 180));
    sint = sin(angle * (M_PI / 180));

    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++)
        {
            double x2, y2, i, j, dist;
            float p, threshold = .5;
            int invert = 0;

            x2 = x + .5;
            y2 = y + .5;
            i = (cost * x2 - sint * y2) / r;
            j = (cost * y2 + sint * x2) / r;
            i = i - (int)i + (i < 0.);
            j = j - (int)j + (j < 0.);

            if(j > 0.5)
	    {
                i = 1. - i;
                j = 1. - j;
            }
            if(i > 0.5)
            {
                invert = 1;
                i = 1. - i;
            }

            dist = (i - .25) * (i - .25) + (j - .25) * (j - .25);
            threshold = dist * 4;
            if(invert)
                threshold = 1. - threshold;

            p = dstdata[y * w + x];
            dstdata[y * w + x] = p > threshold ? 1. : 0.;
        }
    }

    return dst;
}