-- returns the Vector3 point at the given t value, where t is relative to the length of the Bezier curve
-- does not work if the bezier does not have any points attached to it

function Bezier:CalculatePositionRelativeToLength(t: number): Vector3
	
	-- check if t is a number between 0 and 1
	if type(t) ~= "number" then
		error("Bezier:CalculatePositionRelativeToLength() only accepts a number, got " .. tostring(t) .. "!")
	end
	
	-- start algorithm to calculate position in bezier
	local points = self.Points
	local numPoints = #points
	
	-- check if there is at least 1 point
	if numPoints > 0 then
		
		-- important values
		local length = self.Length
		local lengthIndeces = self.LengthIndeces
		local iterations = self.LengthIterations
		local points = self:GetAllPoints()
		
		-- check if there is more than 1 point
		if #points > 1 then
			
			-- 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 p0, p1
			if lengthIndeces[nearestParameterIndex - 1] then
				p0, p1 = self:CalculatePositionAt(lengthIndeces[nearestParameterIndex - 1][1]), self:CalculatePositionAt(nearestParameter[1])
			else
				p0, p1 = self:CalculatePositionAt(nearestParameter[1]), self:CalculatePositionAt(lengthIndeces[nearestParameterIndex + 1][1])
			end
			local percentError = (nearestParameter[2] - targetLength) / (p1 - p0).Magnitude
			
			-- return the position at the nearestParameter
			return p0 + (p1 - p0) * (1 - percentError)
		else
			
			-- return only position
			return self:CalculatePositionAt(0)
		end
	else
		
		-- not enough points to get a position
		error("Bezier:CalculatePositionRelativeToLength() only works if there is at least 1 BezierPoint!")
	end
end

