Some error checking and better logic