#include <webots/robot.h>
#include <webots/servo.h>
#include <stdio.h>
#define NUM_SERVOS 	6
#define NUM_STATES 	2
#define RATE 	 	1.0/6
#define smallSwap	2 * M_PI * RATE
#define bigSwap		2 * M_PI * (1-RATE)
#define TIME_STEP 	16
#define AJUST_PERIOD 	50
int main() {
	const char *SERVO_NAMES[] = {
        "servo_r0",
        "servo_r1",
        "servo_r2",
        "servo_l0",
        "servo_l1",
        "servo_l2"
	};
	WbDeviceTag servos[NUM_SERVOS];
  
	const int 	goForward	[] = { 1, 1, 1, 1, 1, 1};
	const int 	goBackward	[] = {-1,-1,-1,-1,-1,-1};
	const int 	turnLeft	[] = { 1, 1, 1,-1,-1,-1};
	const int 	turnRight	[] = {-1,-1,-1, 1, 1, 1};
	const double posSwap [NUM_STATES][NUM_SERVOS] = {
		{smallSwap	,bigSwap  	,smallSwap	,bigSwap  	,smallSwap	,bigSwap  },
		{bigSwap  	,smallSwap	,bigSwap  	,smallSwap	,bigSwap  	,smallSwap}
	};
	double  pos[NUM_SERVOS] = {
		-smallSwap/2,+smallSwap/2,-smallSwap/2,
		+smallSwap/2,-smallSwap/2,+smallSwap/2
	};
	int i;
	
	
	wb_robot_init();
  
	for (i = 0; i < NUM_SERVOS; i++) {
		servos[i] = wb_robot_get_device(SERVO_NAMES[i]);
		if (!servos[i])
			printf("could not find servo: %s\n",SERVO_NAMES[i]);
	}
	
	const int* dir = turnRight;
	int  state;
	int  elapsed = 0;
	
	
	for (i = 0; i < NUM_SERVOS; i++ )
		pos[i] =  dir[i] * pos[i];
	
	while(wb_robot_step(TIME_STEP)!=-1) { 
	    elapsed++;
		if(elapsed % AJUST_PERIOD!=0) continue;
		state = (elapsed / AJUST_PERIOD + 1) % NUM_STATES;
		for (i = 0; i < NUM_SERVOS; i++ ){
			wb_servo_set_position(servos[i], pos[i]);
			pos[i] += dir[i] * posSwap[state][i]; 
		}
	}
	wb_robot_cleanup();
	return 0;
}