Cleaned up code a bit, added comments