Cleaned up the code a bit, added comments and made some tweaks