#include <stdio.h>
#include <math.h>
// I think we need this include in the project, dunno why
#include "stdafx.h"
// we need kChannelsNum, that defined in common.h
#include "common.h"

// as defined in the paper
const int param_C1=10, param_C2=100, param_C3=355, param_C4=100;

// sensors data at the actual moment
int p_sensor_data_atm[kChannelsNum];
// sensors data at the previous moment
int p_sensor_data_prev[kChannelsNum];
// measured difference
double k_difference[kChannelsNum];

double find_max_element() {
  double tmp=k_difference[0];
  int i;
  
  for(i=1; i<kChannelsNum-1; i++)
    if(tmp<k_difference[i])
      tmp=k_difference[i];
  
  return tmp;
}

double find_min_element() {
  double tmp=k_difference[0];
  int i;
  
  for(i=1; i<kChannelsNum-1; i++)
    if(tmp>k_difference[i])
      tmp=k_difference[i];
  
  return tmp;
}

// making measured slice as defined in the paper
int measured_slice(int num) {
  if(num>(kChannelsNum-1) || num<0) {
    printf("measured_slice: Out of range!\n");

    return -1;
  }

  if((p_sensor_data_atm[num]-p_sensor_data_prev[num])>255)
    return 255;

  else if ((p_sensor_data_atm[num]-p_sensor_data_prev[num])<0)
    return 0;

  else
    return (p_sensor_data_atm[num]-p_sensor_data_prev[num]);
}

void init_difference() {
  int i;

  for(i=0; i<kChannelsNum-1; i++) {
    k_difference[i]=(double)param_C1*measured_slice(i)*sqrt((param_C2+p_sensor_data_atm[i])/param_C3);
}

int main_function_alg_1() {
  double param_kappa, k_max, k_min;
  const double param_kappa0=2.0;
  const double param_A=0.5;
  int i;

// somehow we have to initialize data from the sensors
// p_sensor_data_atm, p_sensor_data_atm
//
// probably this problem is connected to function FAllertLibStartPush?
//
// afterwards initialize k_j(t), as stated in the paper
  init_difference();

// then we calculate thresholds
  k_max=find_max_element();
  k_min=find_min_element();
  param_kappa=(double)((param_C4+k_max)/(param_C4+k_min));

  if(param_kappa<=param_kappa0) {
    printf("Non inhomogeneity found!\n");

    return 0;
  }

  else {
    for(i=0; i<kChannelsNum-1; i++) {
      if(k_difference[i]>(1-param_A)*k_min+param_A*k_max)
	printf("Inhomogeneity found at %d sensor!\n", i);
    }
  }

  return 1;
}