Simplified the main loop slightly