Cleaned up code a bit and added comments