#include <webots/robot.h>
#include <webots/light_sensor.h>

#include <stdio.h>

#define NB_SENSORS 8
#define TIME_STEP 32
#define LS_FILENAME "ls_values.txt"

int main(int argc, const char *argv[]) {
  int i;
  WbDeviceTag ls[NB_SENSORS];
  double ls_value[NB_SENSORS];

  wb_robot_init();

  // get an enable light sensors
  char ls_name[] = "ls0";
  for (i = 0; i < NB_SENSORS; ++i) {
    ls[i] = wb_robot_get_device(ls_name);
    wb_light_sensor_enable(ls[i], TIME_STEP);
    ++ls_name[2];
  }
  
  // open output file
  FILE* ls_file = fopen(LS_FILENAME, "w");
  printf("Writing light sensor values to %s/controllers/%s/%s\n", wb_robot_get_project_path(), wb_robot_get_controller_name(), LS_FILENAME);
  
  // main loop
  double elapsed = 0.0;
  while(wb_robot_step(TIME_STEP)!=-1) {
    elapsed += TIME_STEP / 1000.0;
    
    // read sensor values and compute average
    double ls_avg = 0.0;
    for (i = 0; i < NB_SENSORS; ++i) {
      ls_value[i] = wb_light_sensor_get_value(ls[i]); // range: 0 (far) to 3800 (close)
      ls_avg += ls_value[i];
    }
    ls_avg /= NB_SENSORS;
    
    // write average light sensor value to file
    fprintf(ls_file, "%f %f\n", elapsed, ls_avg);
    fflush(ls_file);
  }
  
  fclose(ls_file);
  wb_robot_cleanup();
  return 0;
}
