#define disconnected 1
#define tryConnect 2
#define connecting 3
#define connected 4

int analogPinOne = 1;
int analogPinTwo = 2;
int digPinC = 3;
int digPinX = 4;

int state = disconnected;

boolean start = false;

int analogValOne;
int analogValTwo;

int thresholdOne = 642;
int thresholdTwo = 658;

void setup(){
pinMode(digPinC, INPUT);
pinMode(digPinX, INPUT);

Serial.begin(9600);
}

void loop(){
stateSwitch();
}

///////////////////////////////////////////////////////////////
void connect(){
Serial.print("C128.122.151.187/8080\n\r");
state = connecting;
}

///////////////////////////////////////////////////////////////
void waitForResponse(){
if (Serial.available() > 0){
int tmpRead = Serial.read();
if (tmpRead == 104){
state = connected;
Serial.flush();
}
}
}

///////////////////////////////////////////////////////////////
void playing(){
if (Serial.available() > 0){
int tmpRead = Serial.read();
if(tmpRead == 98){
state = disconnected;
}
}

analogValOne = analogRead(analogPinOne);
analogValTwo = analogRead(analogPinTwo);
if (analogValOne > thresholdOne){
Serial.print("r");
int tmpDelay = 30 - int((analogValOne - thresholdOne)/6.2);
delay(tmpDelay);
}
if (analogValTwo > thresholdTwo){
Serial.print("l");
int tmpDelay = 30 - int((analogValTwo - thresholdTwo)/4.9);
delay(tmpDelay);
}

if (digitalRead(digPinX) == HIGH){
Serial.print("x");
}
}

///////////////////////////////////////////////////////////////
void waitForJoin(){
if (digitalRead(digPinC) == HIGH){
state = tryConnect;
}
}

///////////////////////////////////////////////////////////////
void stateSwitch(){
switch(state){

case tryConnect:
connect();
break;

case connecting:
waitForResponse();
break;

case connected:
playing();
break;

case disconnected:
waitForJoin();
break;
}
}