Adding in some error checking and cleaning up a little bit