Tidied up main loop and added back and foreground