function init()
	excavator = FindVehicle("excavator")

	direction = nil
	
	baseMotor = FindJoint("excavatorBase")
	arm1Motor = FindJoints("excavatorArm1")
	arm2Motor = FindJoints("excavatorArm2")
	bracketMotor = FindJoints("excavatorBracket")
	motorTable = {baseMotor, arm1Motor, arm2Motor, bracketMotor}
	
	base_spd = 0.5
	arm1_spd = 0.5
	arm2_spd = 1.5
	bracket_spd = 1.5
	
	uiCaption = {'Excavator Commands'}
	uiHotkeys = {{'Left/Right Arrow', 'Pivot Chassis'}, {'Up/Down Arrow', 'Lift Arm&Bracket'}}
end

function draw()
	if GetPlayerVehicle() == excavator then
		local kw = 0
		local vw = 0
		for i=1, #uiHotkeys do
			UiFont("bold.ttf", 22)
			local w0 = UiGetTextSize(uiHotkeys[i][1])
			UiFont("regular.ttf", 22)
			local w1 = UiGetTextSize(uiHotkeys[i][2])
			kw = math.max(kw,w0)
			vw = math.max(vw,w1)
		end
	
		local uiwidth = kw + vw + 120
		local uiheight = #uiHotkeys*26 + 55
		if uiwidth <= 270 then uiwidth = 270 end
		
		UiAlign("left")
		UiTranslate(UiWidth()-uiwidth-20, 20)
		UiColor(0,0,0,0.4)
		UiImageBox("ui/common/box-solid-6.png", uiwidth, uiheight, 6, 6)
		UiTranslate(uiwidth*0.5, 24)
		UiAlign("center middle")
		UiColor(1, 1, 1)
		UiFont("bold.ttf", 26)
		UiText(uiCaption[1])
		UiTranslate(45-(uiwidth-270)*0.25, 36)
		for i=1, #uiHotkeys do
			UiFont("bold.ttf", 22)
			UiAlign("right")
			UiText(uiHotkeys[i][1])
			UiTranslate(20, 0)
			UiFont("regular.ttf", 22)
			UiAlign("left")
			UiText(uiHotkeys[i][2])
			UiTranslate(-20, 26)
		end
	end
end

function MotorInitialize()
	SetJointMotor(baseMotor, 0)
	for i=1,#arm1Motor do
		SetJointMotor(arm1Motor[i], 0)
	end
	for i=1,#arm2Motor do
		SetJointMotor(arm2Motor[i], 0)
	end
	for i=1,#bracketMotor do
		SetJointMotor(bracketMotor[i], 0)
	end
end

function Pivot(directionP)
	if directionP == 'CW' then
		SetJointMotor(baseMotor, -base_spd)
	elseif directionP == 'CCW' then
		SetJointMotor(baseMotor, base_spd)
	end
end

function Lift(direction)
	if direction == 'up' then
		for i=1,#arm1Motor do
			SetJointMotor(arm1Motor[i], -arm1_spd)
		end
		for i=1,#arm2Motor do
			SetJointMotor(arm2Motor[i], -arm2_spd)
		end
		for i=1,#bracketMotor do
			SetJointMotor(bracketMotor[i], -bracket_spd)
		end
	elseif direction == 'down' then
		for i=1,#arm1Motor do
			SetJointMotor(arm1Motor[i], arm1_spd)
		end
		for i=1,#arm2Motor do
			SetJointMotor(arm2Motor[i], arm2_spd)
		end
		for i=1,#bracketMotor do
			SetJointMotor(bracketMotor[i], bracket_spd)
		end
	end
end

function tick(dt)
	if GetPlayerVehicle() == excavator then
		if InputDown("leftarrow") then
			directionP = 'CCW'
			Pivot(directionP)
		elseif InputDown("rightarrow") then
			directionP = 'CW'
			Pivot(directionP)
		
		elseif InputDown("uparrow") then
			direction = 'up'
			Lift(direction)
		elseif InputDown("downarrow") then
			direction = 'down'
			Lift(direction)
			
		else
			MotorInitialize()
		end
	end

end