Refactored foreground so it could be reloaded

But now foreground's logic is too large. Better than having it crammed
into main, but still needs love.