Cleaned up the code; added more comments