Cornering fog lights / turning assistant.

SORTED

/* Light turning assistant for cars (cornering lights)
 Credits to users Dr_P and jucole at http://mjlorton.com forum
 
 Version designed for use with relays equipped with photocoupler (JD-VCC pin)
 (Pinout bank 1: [[JD-VCC, VCC]], GND;                        Pinout bank 2: GND, IN1, IN2, VCC)
 More details about reversed connection: http://arduino.cc/forum/index.php?topic=79745.0
 
 
 */

int fogL = 8;                               // 55W Relay for L fog lamp
int fogR = 7;                               // 55W Relay for R fog lamp
int indL = 4;                               // Circuit between multiswitch and indicator relay
int indR = 2;                               // Circuit between multiswitch and indicator relay
int swBoth = 3;                           // Separate switch for both fog lights


void setup()  {
  pinMode(fogL, OUTPUT); 
  pinMode(fogR, OUTPUT); 
  pinMode(indL, INPUT);
  pinMode(indR, INPUT);
  pinMode(swBoth, INPUT);
}

void loop() {

  int i=100; // counter initialized with "done" value

  if(digitalRead(indR)) {
    i=0; //if indicators were reversed, the cycle needs to be reset to full 5s
    while(digitalRead(indR) && i<100) {
      i++;
      if(! digitalRead(swBoth) ) {
        digitalWrite(fogR, LOW);
        digitalWrite(fogL, HIGH);
      }
      else {
        digitalWrite(fogR, LOW);
        digitalWrite(fogL, LOW);
      }
      delay(50);
    }
  }

  if(digitalRead(indL)) { //same as right side
    i=0;
    while(digitalRead(indL) && i<100) {
      i++;
      if(! digitalRead(swBoth) ) {
        digitalWrite(fogR, HIGH);
        digitalWrite(fogL, LOW);
      }
      else {
        digitalWrite(fogR, LOW);
        digitalWrite(fogL, LOW);
      }
      delay(50);
    }
  }

  if(!digitalRead(indR) && !digitalRead(indL)) { // no indicators currently on

    if(! digitalRead(swBoth) ) {

      if(i==100) { //neither indicators were on OR the 5s cycle is over
        if(! digitalRead(swBoth) ) {
          digitalWrite(fogR, HIGH);
          digitalWrite(fogL, HIGH);
        }
        else {
          digitalWrite(fogR, LOW);
          digitalWrite(fogL, LOW);
        }
      }
      else  { //one or both indicators were on for less than 5s
        while(!digitalRead(indR) && !digitalRead(indL) && i<100 && !digitalRead(swBoth)  ) { //but not any more
          i++;                           //finish the 5s cycle in the last foglight configuration
          delay(50);
        }
      }
    }
    else {
      digitalWrite(fogR, LOW);
      digitalWrite(fogL, LOW);
    }
  }
}