local args = {...}

local mods = {}
local ms = peripheral.getMethods("back")
for i = 1, #ms do
    mods[ms[i]] = true
end
assert(mods.getMetaOwner, "Entity Sensor & Introspection Module Required")
-- local can = assert(mods.canvas, "Overlay Glasses Required")()
assert(mods.launch, "Kinetic Augment Required.")
-- local sx, sy = can.getSize()

if not mods.getBlockMeta then print("No block scanner. Automatic mode unavalible.") end


local yaw
local manLaunch
local autoMode
local autoLaunch

local function meta()
    while true do
        local meta = peripheral.call("back", "getMetaOwner")
        yaw = meta.yaw
    end
end



local function test()
    print("Press g to toggle manual mode.")
    if mods.getBlockMeta then
        print("Press a to toggle automatic mode.")
        if args[1] then autoMode = true print("Automatic Lauch mode: ",autoMode) end
    end
    while true do
        local _, char = os.pullEvent("char")
        if char == "g" then
            manLaunch = not manLaunch
            autoLaunch = false
            print("Manual Lauch mode: ",manLaunch)
        elseif mods.getBlockMeta and char == "a" then
            autoMode = not autoMode
            if not autoMode then autoLaunch = false end
            print("Automatic Lauch mode: ",autoMode)
        end
    end
end



local function autoOn()
    while true do
        if autoMode and not manLaunch then
            if peripheral.call("back", "getBlockMeta", 0, -2, 0).name:match("slab") and peripheral.call("back", "getBlockMeta", 0, -3, 0).name == "minecraft:packed_ice" then
                autoLaunch = true
            else
                autoLaunch = false
            end
        end
        sleep(1)
    end
end



local function cardinal(angle)
    local val = math.floor((angle/90) + 0.5)
    return 90*val
end



local function launch()
    while true do
        if manLaunch or autoLaunch then
            peripheral.call("back", "launch", cardinal(yaw), 0, 0.5)
        else
            sleep()
        end
    end
end
local ok, err = pcall(function()
    parallel.waitForAny(meta, test, launch, autoOn)
end)
if not ok and err ~= "Terminated" then
    os.reboot()
end