cleaning up, added comments, some error checking