#define KEYA 4
#define KEYB 5
#define KEYC 6
#define KEYD 7

#define LEDZ 10
#define LEDC 11

#define IDLE 0
#define STARTED 1
#define STATE2  2
#define STATEOK 50
#define STERROR 100

int state = IDLE;

void setup() {
  // put your setup code here, to run once:
  pinMode(KEYA, INPUT);
  pinMode(KEYB, INPUT);
  pinMode(KEYC, INPUT);
  pinMode(KEYD, INPUT);
  pinMode(LEDZ, OUTPUT);
  pinMode(LEDC, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int keyA, keyB, keyC, keyD;

  keyA = digitalRead ( KEYA );
  keyB = digitalRead ( KEYB );
  keyC = digitalRead ( KEYC );
  keyD = digitalRead ( KEYD );
  
  if ( (keyA + keyB + keyC + keyD) == 1 ) {
    delay(200);
    switch ( state ) {
    case IDLE:
      Serial.println("IDLE");
      if ( keyA ) state = STARTED;
      else state = STERROR;
      Serial.println("NEW: " + String(state));
      break;
    case STARTED:
      Serial.println("STARTED");
      if ( keyD ) state++;
      else state = STERROR;
      Serial.println("NEW: " + String(state));
      break;
    case STATE2:
      Serial.println("STATE2");
      if ( !keyC ){
        state = STERROR;
        break;
      }
      Serial.println("NEW: " + String(state));
    case STATEOK:
      Serial.println("STATOK");
      digitalWrite( LEDZ, HIGH );
      delay(10000);
      Serial.println("NEW: " + String(state));
      state = IDLE;
      break;
    case STERROR:
      digitalWrite( LEDC, HIGH );
      if ( keyB ) { 
        state = IDLE;
        delay ( 200 );
      } else delay(1000);
      break;
    }
  }
}