package yi.iu.processor.morph;

import java.awt.*;
import java.util.*;

/**
 * Locally equalization
 */

public class LocalEqualization extends Morph
{
  public LocalEqualization(int st, int s) {
    super(st, s);
  }

  public int[] getProcessed(int source[], Dimension d) {
    int width = d.width, height = d.height;
    int[] result = new int[width * height];

    boolean[] stct = getStruct();
    int r = (size - 1) / 2;

    for (int i = 0; i < height; i++) {
      for (int j = 0; j < width; j++) {
        LinkedList neigbors = new LinkedList(); //store the gray level of neighbors and itself
        for (int m = 0; m < size; m++) {
          for (int n = 0; n < size; n++) {
            if (!stct[m * size + n])
              continue;
            int y = i + m - r;
            int x = j + n - r;
            if (x < 0 || x >= width)
              continue;
            if (y < 0 || y >= height)
              continue;
            neigbors.add(new Integer(source[y * width + x]));
          }
        }
        int[] grays = yi.util.data.Conversion.toIntArray(neigbors);
        // sort the gray values
        Arrays.sort(grays);
        // find the first and last index of the gray level of current pixel
        int current = source[i * width + j];
        int index = Arrays.binarySearch(grays, current);
//        int first_index = index, last_index = index;
//        while (first_index > 0 && grays[first_index - 1] == current) first_index --;
//        while (last_index + 1 < grays.length && grays[last_index + 1] == current) last_index++;
        result[i * width + j] = 255 * index / (grays.length - 1);
      }
    }
    return result;
  }

}
