int b;

void main()
{
  setup();
  round();
}

int light()
{
return analog(19);
}

void signal()
{
  b=140;
  if(light() < b)
    beep();
}

void turn_front()
{
  while(start_button() == 1)
  ccw_ninety();
}

void setup()
{
  while(stop_button() == 0)
    turn_front();
  b=140;
  while(start_button() == 0)
    signal();
  while(light() > b)
    printf("\nwaiting...");
  printf("\nround has begun");
}

void round()
{
  printf("\nstarting");
  reset_system_time();
  start();
  sleep(60.0);
  stop();
}

void start()
{
  ir_transmit_on();
  begin();
}

void stop()
{
  ao();
  ir_transmit_off();
  disable_servos();
  system_pwm_off();
  printf("\nround has ended");
}

int x;
int a;
int z;
int c;
int n;

/*
orientation of robot should be

    FRONT
R ######### L
I #   #   # E
G # 1 #   # F
H #   #   # T
T #########
  #   #   #
  # 2 # 3 #
  #   #   #
  #########
    BACK

*/

int light_one()
{
  return analog(16);
}

int light_two()
{
  return analog(17);
}

int light_three()
{
  return analog(18);
}

int orientation()
{
  a=70;
  z=35;
  c=140;
  if(light_one() < a && light_two() < z && light_three() < c)
    return 0;
  if(light_one() > a && light_two() > z && light_three() > c)
    return 0;
  if(light_one() < a && light_two() < z && light_three() > c)
    return 1;
  if(light_one() > a && light_two() > z && light_three() < c)
    return 1;
  if(light_one() < a && light_two() > z && light_three() > c)
    return 2;
  if(light_one() > a && light_two() < z && light_three() < c)
    return 2;
  if(light_one() < a && light_two() > z && light_three() < c)
    return 3;
  if(light_one() > a && light_two() < a && light_three() > a)
    return 3;
}


int break_beam()
{
  return analog(20);
}

void turn()
{
  instructions(orientation());
}

void instructions(int l)
{
  if (l == 0)
    printf("IN POSITION\n");
  if (l == 1)
    ccw_two_seventy();
  if (l == 2)
    ccw_ninety();
  if (l == 3)
    ccw_one_eighty();
}

void cw_base()
{
  fd(4);
  fd(5);
}

void ccw_base()
{
  bk(4);
  bk(5);
}

void stop_base()
{
  off(4);
  off(5);
}

void ccw_two_seventy()
{
  n=25;
  cw_base();
  sleep(0.5);
  while (break_beam() < n)
    cw_base();
  stop_base();
}

void ccw_one_eighty()
{
  ccw_ninety();
  ccw_ninety();
}

void ccw_ninety()
{
  n=25;
  ccw_base();
  sleep(0.5);
  while (break_beam() < n)
    ccw_base();
  stop_base();
}

void begin()
{
  turn();
  easy();
}

void easy()
{
  forward();
  sleep(1.9);
  hard_left();
  sleep(0.95);
  forward();
  sleep(0.75);
  back();
  sleep(1.3);
  car_stop();
  sleep(18.0);
  forward();
  sleep(1.0);
  back();
  sleep(1.2);
  car_stop();
  sleep(19.0);
  forward();
  sleep(1.0);
  car_stop();
}

void back()
{
  bk(0);
  bk(2);
}

void forward()
{
  fd(0);
  fd(2);
}

void hard_left()
{
  fd(2);
  bk(0);
}

void car_stop()
{
  off(0);
  off(2);
}