Cleaned up code and added comments for clairty.