-- This Source Code Form is subject to the terms of the bCDDL, v. 1.1.
-- If a copy of the bCDDL was not distributed with this
-- file, You can obtain one at http://beamng.com/bCDDL-1.1.txt
local M = {}

local function onInit()
    electrics.values['4ws'] = 0
end

local function updateGFX(dt)
    if not electrics.values['steering_input'] then return end
    local speed = electrics.values["wheelspeed"]
	local dirVector = obj:getDirectionVector()
	local dirVectorUp = obj:getDirectionVectorUp()
    local airSpeed = electrics.values["airspeed"] / 2
    local steer = -electrics.values['steering_input']
    local roll = math.abs(dirVector.x)
    local gForceX = math.abs(sensors.gx / 9.81)
    local gForceY = math.abs(sensors.gy / 9.81)
    local pitch = math.abs(dirVector.z)
    local absSteer = math.abs(steer)
    local rws = 0	
	
	if airSpeed <= 24 then
        speed = speed + (speed * 0.75)
	end
	
	if (speed + airSpeed) <= 12 or math.abs(roll) <= (pitch) then
    rws = (((speed + airSpeed) / 2 - 12) / 10) * absSteer
	elseif (speed + airSpeed) > 12 and math.abs(roll) >= (pitch) then
	if gForceX < (gForceY) then
    rws = absSteer * 0.6
	else
    rws = (math.sin(absSteer * 1) * math.cos((absSteer * 3.3))) * 1.21
	end
	end
	
	
    rws = rws * fsign(steer) --Use the sign of the steering input to know the sign of rws output
	
    electrics.values['4ws'] = rws
end

-- public interface
M.onInit      = onInit
M.onReset     = onInit
M.updateGFX = updateGFX

return M