added comments and error check