Added a lot of error checking and some code clean up