cleaned up code and added more error checking