Added some comments and tweaked the main loop