rcar $car = get local car	//get car

rcarmodel $ileft  = get generic model 1 of $car   //Left indicator
rcarmodel $iright = get generic model 2 of $car   //Right one
set $ileft  scriptcontrolled 1
set $iright scriptcontrolled 1

int $ldown=0
int $rdown=0
int $litdown=0

int $lefton=0			//Are they on?
int $righton=0
shared int $liton=0

int $duration=0			//Stay lit duration, max 500ms
int $direction=1		//Lit or Pause

int $gear=0
int $lastgear=0			//Last known gear

func void CheckInput()		//Check for input
{
  if is key 81 pressed		//Left signal key [Q]
  {
    if $ldown == 0		//First press
    {
      $ldown = 1		//Mark as held down
      if $lefton == 1
      {
        $lefton = 0		//If On, cancel it
      }
      else 
      {
         $lefton = 1		//Turn it on 
         $righton = 0		//Cancel oposite signal
      }
    }
  }
  else
  {
    $ldown = 0			//Mark as released
  }

  if is key 69 pressed		//Right signal key [E]
  {
    if $rdown == 0		//First press
    {
      $rdown = 1		//Mark as held down
      if $righton == 1
      {
        $righton = 0		//If On, cancel it
      }
      else 
      {
         $righton = 1		//Turn it on 
         $lefton = 0		//Cancel oposite signal
      }
    }
  }
  else
  {
    $rdown = 0			//Mark as released
  }

  if is key 76 pressed		//Lights key [L]
  {
    if $litdown == 0		//First press
    {
      $litdown = 1		//Mark as held down
      $liton = 1 - $liton	//Toggle
    }
  }
  else
  {
    $litdown = 0		//Mark as released
  }
}

func void CheckReverse()		//Check for reverse
{
  $gear = get $car gear		//If reverse selected,
  if $gear == 1			//Turn on both signals (hazard lights)
  {
    $lefton = 1
    $righton = 1
  }
  else if $lastgear == 1	//Just came out of reverse? 
    {
      $lefton = 0		//Reset them
      $righton = 0
    }
  $lastgear = $gear		//update last gear
}

func void TimeBlinking()		//Compute blinking time
{
  int $oneactive = $lefton + $righton
  if $oneactive > 0		//Least one of them active
  {
				//Compute time passed
    $duration = $duration + interval * $direction

    if $duration > 500		//Has been lit for half a sec  
    { 
      $duration = 500 		//Cap it
      $direction = -1		//Switch bulb off
    }
    if $duration < 0 		//Has been sleeping for half a sec
    { 
      $duration = 0		//Cap it  
      $direction =  1		//Turn bulb on
    }
  }
  else				//None is active
  {
    $duration = 0
    $direction = 1
  }
}

func void ShowSignals()		//Show models
{
  if $lefton + $direction > 1	//On and lit, show 3d model
  {
    set $ileft position float[3]{0,0,0}
  }
  else				//Hide it
  {
    set $ileft position float[3]{0,-0.2,0}
  }

  if $righton + $direction > 1	//On and lit, show 3d model
  {
    set $iright position float[3]{0,0,0}
  }
  else				//Hide it
  {
    set $iright position float[3]{0,-0.2,0}
  }

}

while 1
{
  CheckInput()
  CheckReverse()
  TimeBlinking()
  ShowSignals()
  
  interrupt
}