Cleaned up the code and commented for clarity.