Added error handling, code commnets, and restructured code to be more efficient in some cases