if not goroutine then
  if not os.loadAPI("goroutine") then
    print("goroutine API is required!")
    return
  end
end

--args
local args={...}

local function usage()
  print("usage:\nbg <program> [args...]")
  error()
end

if #args<1 then 
  usage() 
end

local program=args[1]

program=shell.resolveProgram(program)
if not program then
  print("Couldn't find program '"..program.."'!")
  return
end

local name=program
local index=0
while goroutine.findNamedCoroutine(name) do
  index=index+1
  name=program..index
end

if goroutine.isActive() then
  --just spawn!
  print("Spawning '"..program.."' in background.")
  
  goroutine.spawnBackground(name, shell.run, ...)
  
else
  --not running we have to run ourselves.
  local function main(...)
    goroutine.spawnBackground(name, shell.run, ...)
    print("Launching new local shell. Exit this shell to terminate monitor program!")
    shell.run("shell")
  end
  goroutine.run(main,...)
end