-- returns the tangent vector in the direction of the path made by the bezier at t (where t is relative to the length of the Bezier Curve)
-- does not work if the bezier does not have at least 2 points
-- the given t value must be between 0 and 1

function Bezier:CalculateDerivativeRelativeToLength(t: number): Vector3
	
	-- check if t is a number between 0 and 1
	if type(t) ~= "number" then
		error("Bezier:CalculateDerivativeRelativeToLength() only accepts a number, got " .. tostring(t) .. "!")
	end
	
	-- start algorithm to calculate derivative in bezier
	local points = self.Points
	local numPoints = #points
	
	-- check if there are at least 2 points
	if numPoints > 1 then
		
		-- important values
		local length = self.Length
		local lengthIndeces = self.LengthIndeces
		local iterations = self.LengthIterations
		local points = self:GetAllPoints()

		-- get length of bezier
		local targetLength = length * t

		-- iterate through sum table
		local nearestParameterIndex, nearestParameter
		for i, orderedPair in ipairs(lengthIndeces) do
			if targetLength - orderedPair[2] <= 0 then
				nearestParameterIndex = i
				nearestParameter = orderedPair
				break
			elseif i == #lengthIndeces then
				nearestParameterIndex = i
				nearestParameter = orderedPair
				break
			end
		end

		-- calculate percent error
		local d0, d1
		if lengthIndeces[nearestParameterIndex - 1] then
			d0, d1 = self:CalculateDerivativeAt(lengthIndeces[nearestParameterIndex - 1][1]), self:CalculateDerivativeAt(nearestParameter[1])
		else
			d0, d1 = self:CalculateDerivativeAt(nearestParameter[1]), self:CalculateDerivativeAt(lengthIndeces[nearestParameterIndex + 1][1])
		end
		local percentError = (nearestParameter[2] - targetLength) / (d1 - d0).Magnitude

		-- return the derivative at the nearestParameter
		return d0 + (d1 - d0) * (1 - percentError)
	else
		
		-- not enough points to calculate derivative
		error("Bezier:CalculateDerivativeRelativeToLength() only works if there are at least 2 BezierPoints!")
	end
end

