local carNode = ac.findNodes('carRoot:0')
local animDir = ac.getFolder(ac.FolderID.ContentCars) .. '/' .. ac.getCarID(0) .. '/animations/steeringwheel.ksanim' 
local animDir2= ac.getFolder(ac.FolderID.ContentCars) .. '/' .. ac.getCarID(0) .. '/animations/driver_steer.ksanim' 
local carSounds = ui.MediaPlayer()
local engineOn = false
local previousGear = ac.getCar(0).gear
local currentGear = ac.getCar(0).gear
local lut, lut2
lut = ac.DataLUT11.parse("| -360=0.0 | 0=0.5 | 360=1.0 |")
lut2 = ac.DataLUT11.parse("| 0=1.0 | 40=0.0 | 300=-0.5 |")
carSounds:setSource('./start.ogg')
carSounds:setLooping(false)
carSounds:setVolume(ac.getAudioVolume('main') * 1)

function counterSteering()
  carNode:setAnimation(animDir, lut.get(lut,ac.getCar(0).steer*lut2.get(lut2,ac.getCar(0).speedKmh)), true)
  carNode:setAnimation(animDir2, lut.get(lut,ac.getCar(0).steer*lut2.get(lut2,ac.getCar(0).speedKmh)), true)
end

local driver = ac.findNodes('DRIVER:DRIVER')
driver:storeCurrentTransformation()

function kickstand()
  if ac.getCar(0).extraB or ac.getCar(0).extraC then
    driver:setVisible(false)
  else
    driver:setVisible(true)
  end
end

local counter=0

function startEngine(dt)
  if ac.getCar(0).rpm < 800 and ac.getCar(0).speedKmh < 1 then
    if ac.getCar(0).gas >= 0.1 and (ac.getCar(0).clutch < 0.5 or ac.getCar(0).gear == 0) then
    carSounds:play()
    engineOn = true --and carSounds:ended() 
    else
      counter = 0
      engineOn = false --and carSounds:ended() 
    end
	end
  counter = counter + dt
  if engineOn and counter > 0.1 then
    ac.CarAudioTweak.setVolume(ac.CarAudioEventID.EngineExt, 1)
    ac.CarAudioTweak.setVolume(ac.CarAudioEventID.EngineInt, 1)
  else
    ac.CarAudioTweak.setVolume(ac.CarAudioEventID.EngineExt, 0)
    ac.CarAudioTweak.setVolume(ac.CarAudioEventID.EngineInt, 0)
  end
end

function gearSound()
  if currentGear ~= ac.getCar(0).gear then
    previousGear = currentGear
    currentGear = ac.getCar(0).gear
  end
  if (ac.getCar(0).gear == 1 or ac.getCar(0).gear == -1) and previousGear == 0 then
    ac.CarAudioTweak.setVolume(ac.CarAudioEventID.GearExt, 1)
    ac.CarAudioTweak.setVolume(ac.CarAudioEventID.GearInt, 1)
  else
    ac.CarAudioTweak.setVolume(ac.CarAudioEventID.GearExt, 0.15)
    ac.CarAudioTweak.setVolume(ac.CarAudioEventID.GearInt, 0.15)
  end
end

function script.update(dt)
  counterSteering()
  kickstand()
  startEngine(dt)
  gearSound() 
end