Cleaned up code, removed most debugging print statements, and split large functions into smaller helper functions.