Cleaned up the code, added comments