Added a mainloop with event handling.
Made the background clear properly.
Moved some code into functions.