Cleaned up code, added comments, fixed timing issue