Simplified logic, removed unnecessary code, and added additional documentation.