Cleaned up code, added comments and some error handling