Added comments. Cleaned up formatting and logic.