Clarified the code and description. Also added comments and fixed a few bugs.