Clean up, comment, and add error handling to the JavaScript