function map(x, in_min, in_max, out_min, out_max)
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
end

local calcDistance = require("externals")

function turn(context)
    if context.up then
        send("H200")
        context.up = false
    end

    if context.down then
        send("H800")
        context.down = false
    end

	angle = angleToAnchor(context.idx)
    if math.abs(angle) > 0.314 and (context.prev ~= 3 or context.prev ~= 4 or context.prev ~= 0) then
        if angle > 0 then
            if context.prev ~= 1 then
                send("S2310")
                send("E0110")
                setText("R")
                context.prev = 1
                context.prevTime = os.clock()
            end
        else
            if context.prev ~= 2 then
                send("S1000")
                send("E0110")
                setText("L")
                context.prev = 2
                context.prevTime = os.clock()
            end
        end
    elseif math.abs(angle) > 0.1 and (context.prev == 0 or context.prev == 3 or context.prev == 4) then
        if (os.clock() - context.prevTime) > 0.250 then
            if angle > 0 then
                send("S" .. tostring(map(angle, 0.314, 0.05, 2000, 1650)))
                setText("R " .. tostring(map(angle, 0.314, 0.05, 2000, 1650)))
                context.prev = 3
                context.prevTime = os.clock()
            else
                send("S" .. tostring(map(math.abs(angle), 0.314, 0.05, 1000, 1650)))
                setText("L " .. tostring(map(math.abs(angle), 0.314, 0.05, 1000, 1650)))
                context.prev = 4
                context.prevTime = os.clock()
            end
        end
    elseif context.prev ~= 0 then
        send("S1650")
        send("E0110")
        setText("F")
        context.prev = 0
        context.prevTime = os.clock()
    end
    return calcDistance(context.idx) < 0.3
end
return turn