#include <stdio.h>

#include "bitmap_24bitRGB.h"
#include "bitmap_8bit.h" 
#include "bitmap_2bit.h" 
#include "image_conversion.h"


Bitmap_8bit * convert_24bitRGB_to_8bit(Bitmap_24bitRGB *rgbBmp) {
  Bitmap_8bit *grayBmp = NULL;
  int x, y;
  unsigned char value;
  Pixel_24bitRGB rgbPixel;

  grayBmp = create_bmp8bit(rgbBmp->width, rgbBmp->height);
  if(grayBmp == NULL) {
    perror("convert_24bitRGB_to_8bit");
    return NULL;
  }
  
  for( y=0 ; y < rgbBmp->height ; y++ ) {
    for( x=0; x < rgbBmp->width ; x++ ) {
      rgbPixel = getPixel_bmp24bitRGB(rgbBmp, x, y);
      value = (unsigned char) (
	(rgbPixel.red + rgbPixel.green + rgbPixel.blue) / 3 );
      setPixel_bmp8bit(grayBmp, x, y, value);
    }
  }
  return grayBmp;
}

Bitmap_2bit * threshold_8bit(Bitmap_8bit *source, unsigned char threshold) {
  Bitmap_2bit *result;
  int y, x;
  unsigned char value;

  result = create_bmp2bit(source->width, source->height);
  if(result == NULL) {
    perror("threshold_8bit, create_bmp2bit");
    return NULL;
  }

  for(y=0; y < source->height; y++) {
    for(x=0; x < source->width; x++) {
      value = getPixel_bmp8bit(source, x, y);
      if(value < threshold) {
	setPixel_bmp2bit(result, x, y, 0);
      }
      else {
	setPixel_bmp2bit(result, x, y, 1);
      } 
    }
  }

  return result;
}

static unsigned char median_8_neighbour(Bitmap_8bit *source, int x, int y){
  unsigned char p[9], temp;
  int k, l;
  int w = source->width;
  unsigned char *in = source->image;

  /* this section loads the center pixel and its surrounding neighbors 
   * into an array  
   */          
  p[0] = in[(y-1)*w +x-1]; p[1] = in[(y-1)*w +x]; p[2] = in[(y-1)*w +x  ]; 
  p[3] = in[(y  )*w +x-1]; p[4] = in[(y  )*w +x]; p[5] = in[(y  )*w +x+1];
  p[6] = in[(y+1)*w +x-1]; p[7] = in[(y+1)*w +x]; p[8] = in[(y+1)*w +x+1];

  /* PENDING parempi sorttaus tähän */
  /* we will use a simple bubble sort to sort the values */

  for(k=0; k<8; k++){
    for(l=0; l<(8-k); l++)
      if(p[l] > p[l+1]) {
	temp = p[l]; p[l]=p[l+1]; p[l+1]=temp;
      }
  }
  /* return the middle value to use as the answer */
  return p[4];
}

Bitmap_8bit *medianFilter(Bitmap_8bit * source) {
  int y,x;
  Bitmap_8bit *result;
  
  result = create_bmp8bit(source->width, source->height);
  if(result == NULL) {
    return NULL;
  }

  /* PENDING ei käsittele reunoja */
  for(y=1; y<source->height-1; y++) {
    for(x=1; x<source->width-1; x++) {
      setPixel_bmp8bit(result, x,y,median_8_neighbour(source, x, y));
    }
  }
  return result;
}
