Added comments explaining some of the rules and cleaned up the code a little.