/*
 *  Copyright 1994-2022 Olivier Girondel
 *
 *  This file is part of lebiniou.
 *
 *  lebiniou 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.
 *
 *  lebiniou 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 lebiniou. If not, see <http://www.gnu.org/licenses/>.
 */

#include "context.h"


uint32_t version = 0;
uint32_t options = BO_BLUR;
char desc[] = "Blur filter";
char dname[] = "Chemical blur";


/* TODO optimize this --oliv3 */
void
run(Context_t *ctx)
{
  const Buffer8_t *src = active_buffer(ctx);
  Buffer8_t *dst = passive_buffer(ctx);

  Buffer8_init_mask_3x3(active_buffer(ctx));

  for (uint16_t j = 1; j < MAXY - 1; j++) {
    Pixel_t bcolor = 0;
    for (uint16_t i = 1; i < MAXX - 1; i++) {
      uint8_t flat = 1;
      Pixel_t m, n, s, e, w;
      int16_t t;

      m = get_pixel_nc(src, i, j    );
      n = get_pixel_nc(src, i, j - 1);
      if (n != m) {
        flat = 0;
      }
      s = get_pixel_nc(src, i, j + 1);
      if (s != m) {
        flat = 0;
      }
      e = get_pixel_nc(src, i + 1, j);
      if (e != m) {
        flat = 0;
      }
      w = get_pixel_nc(src, i - 1, j);
      if (w != m) {
        flat = 0;
      }

      t = (n + s + ((e + w + m) << 1)) >> 3; // like blur2

      if (t < 0) {
        t = drand48() * 256;
      }

      if (flat) {
        t = bcolor;
      } else {
        bcolor++;
      }

      set_pixel_nc(dst, i, j, (Pixel_t)(t));
    }
  }

  Buffer8_expand_border(dst);
}
