/* Image Processing and Recognition Module for the IUPGLCAP application. */
/* It should not contain interface code, neither OpenGL nor IUP.         */

#include <stdio.h>
#include <stdlib.h>

#include <im.h>
#include <im_capture.h>
#include <im_image.h>
#include <im_convert.h>
#include <im_process.h>
#include <im_format_avi.h>

static void SetBinary(imImage* image)
{
  int i;
  unsigned char* im_data = (unsigned char*)image->data[0];
  for (i = 0; i < image->count; i++)
  {
    if (*im_data)
      *im_data = 1;
    im_data++;
  }
}

static void FixBinary(imImage* image)
{
  int i;
  unsigned char* im_data = (unsigned char*)image->data[0];
  for (i = 0; i < image->count; i++)
  {
    if (*im_data)
      *im_data = 255;
    im_data++;
  }
}

void arProcessScuri(unsigned char* gl_data, imImage *image,imImage *aux_image, int *flags, double value1, double value2)
{
  if (flags[0])
  {
    float params[3];
    int slice_end = 128, open_iter = 5;  /* these are candidates to be controled by value1 and value2 */

    /* eliminate noise with a gaussian filter of sigma=1 */
    imProcessGaussianConvolve(image, aux_image, 1.0f);

    /* threshold with slice, select black pixels */
    /* the result is a black background with selected pixels in white */
    params[0] = (float)0;
    params[1] = (float)slice_end;
    params[2] = (float)1; /* binarize 0/255 */
    imProcessToneGamut(aux_image, aux_image, IM_GAMUT_SLICE, params);

    SetBinary(aux_image); /* this compensates the returned values in IM_GAMUT_SLICE */

    /* eliminate small areas using morphological opening, 
       Erode+Erode+Erode+...+Dilate+Dilate+Dilate+...
       kernel_size=3 */
    /* the following two operations are highly inneficient */
    /* a scrap operator should be implemented instead. */
    // imProcessScrap(app_data->image, app_data->aux_image, 100, -1);
    imProcessBinMorphErode(aux_image, image, 3, open_iter);
    imProcessBinMorphDilate(image, aux_image, 3, open_iter);

    /* detect borders using morphological outline,
       Erode+Difference
       kernel_size=3, iterations=1 */
    imProcessBinMorphOutline(aux_image, image, 3, 1);

    /* should now eliminate non close-connected components */
    // imProcess...

    /* converts 0-1 to 0-255 */
    FixBinary(image);
  }
}
