if not term.isColor() then
  print("Advanced computer required")
  error()
end

function showError(message)
  term.setBackgroundColor(colors.black)
  term.setTextColor(colors.red)
  term.write(message)
  term.setBackgroundColor(colors.black)
  term.setTextColor(colors.white)
  print()
end

function showErrorAndExit(message)
  showError(message)
  error()
end

local radar
local sides = peripheral.getNames()
for key,side in pairs(sides) do
  if peripheral.getType(side) == "warpdriveRadar" then
    print("Radar found on " .. side)
    radar = peripheral.wrap(side)
  end
end
if radar == nil or radar.interfaced() == nil then
  showErrorAndExit("No radar detected")
end

local argv = { ... }
if #argv ~= 1 then
  showErrorAndExit("Usage: ping <scanRadius>")
end

local radius = tonumber(argv[1])

if radius < 1 or radius > 9999 then
  showErrorAndExit("Radius must be between 1 and 9999")
end

local energy, energyMax = radar.energy()
local energyRequired = radar.getEnergyRequired(radius)
local scanDuration = radar.getScanDuration(radius)
if energy < energyRequired then
  showErrorAndExit("Low energy level... (" .. energy .. "/" .. energyRequired .. ")")
end
radar.radius(radius)
radar.start()
os.sleep(0.5)

print("Scanning... (" .. scanDuration .. " s)")
os.sleep(scanDuration)

local delay = 0
local count
repeat
  count = radar.getResultsCount()
  os.sleep(0.1)
  delay = delay + 1
until (count ~= nil and count ~= -1) or delay > 10

if count ~= nil and count > 0 then
  for i=0, count-1 do
    local success, type, name, x, y, z = radar.getResult(i)
    if success then
      print(type .. " " .. name .. " @ (" .. x .. " " .. y .. " " .. z .. ")")
    else
      showError("Error " .. type)
    end
  end
else
  print("Nothing was found =(")
end
